Python中的`__dict__`类

时间:2012-05-08 11:53:59

标签: python class

代码优先,

#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__包含一个attr - '__dict': <attribute '__dict__' of 'A' objects>。这是什么?适用于a1a2吗?但是A的对象有自己的__dict__,不是吗?

3 个答案:

答案 0 :(得分:4)

关于你的第一个问题,我引用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.

答案 1 :(得分: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

答案 2 :(得分:0)

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

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

进行分配