RT
python 是否存在不能改变 key 的 dict?
dict 的 keys 在定义的时候就规定
没听懂楼主意思,dict的key本身就不能被直接修改,除非先删除再增加,在新建一个dict时完全可以定义key啊
dict = {'k1' : 1,
'k2' : 2,
'k3' : 3}
在对象中使用__slots__
属性。 __slots__
会限制对象只能使用指定的那几个属性。
>>> class SLT:
__slots__ = ['a','b','c']
>>> slt=SLT()
>>> slt.a=0
>>> slt.b
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
slt.b
AttributeError: b
>>> slt.b=99
>>> slt.b
99
>>> slt.d=111
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
slt.d=111
AttributeError: 'SLT' object has no attribute 'd'
>>> slt.x='xxx'
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
slt.x='xxx'
AttributeError: 'SLT' object has no attribute 'x'
4 回答4.4k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
1 回答4.4k 阅读✓ 已解决
1 回答3.8k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
2 回答2k 阅读✓ 已解决
自己改写咯
覆盖
__setitem__
__delitem__
方法