【发布时间】:2020-01-20 10:05:14
【问题描述】:
这里是一个简单的属性dict代码:
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
更多上下文: https://stackoverflow.com/a/14620633/1179925
我可以像这样使用它:
d = AttrDict({'a':1, 'b':2})
print(d)
我希望这成为可能:
d.b = 10
print(d)
但我希望这是不可能的:
d.c = 4
print(d)
是否有可能在创建新密钥时抛出错误?
【问题讨论】:
-
你为什么不创建一个包含字典的对象。这样就无法添加新属性,但可以更改现有属性。
-
@Chognificent Class in python 不保证这一点。
标签: python dictionary attributes