Bar*_*uch 33 python python-3.x
以下似乎无论如何都有效.使用的优点(除了好的repr
)有什么用types.SimpleNamespace
?或者它是一回事吗?
>>> 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'
Run Code Online (Sandbox Code Playgroud)
小智 53
这在类型模块描述中得到了很好的解释.它向您显示types.SimpleNamespace
大致相当于此:
class SimpleNamespace:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __repr__(self):
keys = sorted(self.__dict__)
items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
return "{}({})".format(type(self).__name__, ", ".join(items))
def __eq__(self, other):
return self.__dict__ == other.__dict__
Run Code Online (Sandbox Code Playgroud)
与空类相比,这具有以下优点:
sn = SimpleNamespace(a=1, b=2)
repr()
:eval(repr(sn)) == sn
id()
,而是比较属性值.Mil*_*vić 16
Aclass types.SimpleNamespace
提供了一种实例化对象的机制,该对象可以保存属性而不能保存其他内容。实际上,它是一个空的类,有一个爱好者__init__()
和一个有用的__repr__()
:
>>> from types import SimpleNamespace
>>> sn = SimpleNamespace(x = 1, y = 2)
>>> sn
namespace(x=1, y=2)
>>> sn.z = 'foo'
>>> del(sn.x)
>>> sn
namespace(y=2, z='foo')
Run Code Online (Sandbox Code Playgroud)
或者
from types import SimpleNamespace
sn = SimpleNamespace(x = 1, y = 2)
print(sn)
sn.z = 'foo'
del(sn.x)
print(sn)
Run Code Online (Sandbox Code Playgroud)
输出:
namespace(x=1, y=2)
namespace(y=2, z='foo')
Run Code Online (Sandbox Code Playgroud)
这个答案也可能有帮助。