SimpleNamespace和空类定义有什么区别?

时间:2016-05-11 11:28:16

标签: 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'

2 个答案:

答案 0 :(得分:44)

This is explained pretty well in the types module description. It shows you that types.SimpleNamespace is roughly equivalent to this:

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__

This provides the following advantages over an empty class:

  1. It allows you to initialize attributes while constructing the object: sn = SimpleNamespace(a=1, b=2)
  2. It provides a readable repr(): eval(repr(sn)) == sn
  3. It overrides the default comparison. Instead of comparing by id(), it compares attribute values instead.

答案 1 :(得分:0)

class 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')

from types import SimpleNamespace

sn = SimpleNamespace(x = 1, y = 2)
print(sn)

sn.z = 'foo'
del(sn.x)
print(sn)

输出:

namespace(x=1, y=2)
namespace(y=2, z='foo')

这个answer也可能有帮助。