【问题标题】:What is the difference between SimpleNamespace and empty class definition?SimpleNamespace 和空类定义有什么区别?
【发布时间】:2016-09-06 18:35:10
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    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 也可能有帮助。

    【讨论】:

      【解决方案2】:

      这在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() 进行比较,而是比较属性值。

      【讨论】:

      • 换句话说 1- 它也允许在构造对象时初始化属性:sn = SimpleNamespace(a=1, b=2) 2- 它提供可读的repr()eval(repr(sn)) == sn 3- 它覆盖默认比较(通过@ 987654332@继承自object),比较属性值。
      • jfs 的评论应该是接受的答案的一部分。
      • 知道为什么repr(SimpleNamespace(a=1)) 显示"namespace(a=1)" 吗?我希望它是 SimpleNamespace 而不是简单的命名空间。
      • @Demi-Lune 这是hard-coded。但是,SimpleNamespace 的子类实例有自己的类名。
      • 给我最大的好处 4:它允许我在字典上使用 dot.notation。
      猜你喜欢
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      • 2011-09-25
      相关资源
      最近更新 更多