python 是否存在限制 key 的 dict

RT

python 是否存在不能改变 key 的 dict?
dict 的 keys 在定义的时候就规定

阅读 4.8k
3 个回答

自己改写咯

覆盖 __setitem__ __delitem__ 方法

没听懂楼主意思,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'
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题