以下两种方法似乎都管用。使用types.SimpleNamespace
有什么好处(除了repr
之外)?还是同样的事情?
>>> import types
>>> class Cls():
... pass
...
>>> foo = types.SimpleNamespace() # or foo = Cls()
>>> foo.bar = 42
>>> foo.bar
42
>>> del foo.bar
>>> foo.bar
AttributeError: 'types.SimpleNamespace' object has no attribute 'bar'
这在types模块描述中得到了很好的解释。它表明
types.SimpleNamespace
大致等同于:与空类相比,这提供了以下优势:
sn = SimpleNamespace(a=1, b=2)
repr()
:eval(repr(sn)) == sn
id()
进行比较,而是比较属性值。相关问题 更多 >
编程相关推荐