simplename空间和空类定义有什么区别?

2024-09-27 07:25:07 发布

您现在位置:Python中文网/ 问答频道 /正文

以下两种方法似乎都管用。使用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'

Tags: or方法importobjectfoobarpass事情
1条回答
网友
1楼 · 发布于 2024-09-27 07:25:07

这在types模块描述中得到了很好的解释。它表明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__

与空类相比,这提供了以下优势:

  1. 它允许您在构造对象时初始化属性:sn = SimpleNamespace(a=1, b=2)
  2. 它提供可读的repr()eval(repr(sn)) == sn
  3. 它覆盖默认比较。它不是通过id()进行比较,而是比较属性值。

相关问题 更多 >

    热门问题