【问题标题】:`__dict__` of classes in PythonPython中的类的`__dict__`
【发布时间】:2012-05-16 21:43:05
【问题描述】:

代码先行,

#Python 2.7

>>>class A(object):
       pass

>>>a1 = A()
>>>a2 = A()

>>>A.__dict__
dict_proxy({'__dict__': <attribute '__dict__' of 'A' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None})

问题

1.什么是dict_proxy,为什么要使用它?

2.A.__dict__ 包含一个属性 -- '__dict': &lt;attribute '__dict__' of 'A' objects&gt;。这是什么?是给a1a2 的吗?但是A 的对象有自己的__dict__,不是吗?

【问题讨论】:

    标签: python class


    【解决方案1】:

    我引用 Fredrik Lundh 的第一个问题:http://www.velocityreviews.com/forums/t359039-dictproxy-what-is-this.html

    a CPython implementation detail, used to protect an internal data structure used
    by new-style objects from unexpected modifications.
    

    【讨论】:

      【解决方案2】:

      第二个问题:

      >>> class A(object):
             pass
      
      >>> a1 = A()
      >>> a2 = A()
      >>> a1.foo="spam"
      >>> a1.__dict__
      {'foo': 'spam'}
      >>> A.bacon = 'delicious'
      >>> a1.bacon
      'delicious'
      >>> a2.bacon
      'delicious'
      >>> a2.foo
      Traceback (most recent call last):
        File "<pyshell#314>", line 1, in <module>
          a2.foo
      AttributeError: 'A' object has no attribute 'foo'
      >>> a1.__dict__
      {'foo': 'spam'}
      >>> A.__dict__
      dict_proxy({'__dict__': <attribute '__dict__' of 'A' objects>, 'bacon': 'delicious', '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None})
      

      这能回答你的问题吗?

      如果没有,请深入了解:https://stackoverflow.com/a/4877655/1324545

      【讨论】:

      • 我只是想知道,为什么A.__dict__ 仍然包含'__dict__': &lt;attribute '__dict__' of 'A' objects&gt;,这是A 的实例吗?
      • 是的,但它不是__dict__。它为实例实现 __dict__。这在我发布的链接中进行了解释。
      【解决方案3】:

      dict_proxy 通过将它们分配给__dict__ 来阻止您在类对象上创建新属性。如果你想这样做,请使用setattr(A, attribute_name, value)

      a1 和 a2 是 A 的实例,而不是类对象。他们没有 A 的保护,您可以使用 a1.__dict__['abc'] = 'xyz' 进行分配

      【讨论】:

        猜你喜欢
        • 2011-06-20
        • 2011-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多