3

代码先行,

#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': <attribute '__dict__' of 'A' objects>。这是什么?是为了a1a2吗?但是对象A有自己的__dict__,不是吗?

4

3 回答 3

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.
于 2012-05-08T11:55:51.897 回答
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

于 2012-05-08T12:16:15.903 回答
0

dict_proxy prevents you from creating new attributes on a class object by assigning them to the __dict__. If you want to do that use setattr(A, attribute_name, value).

a1 and a2 are instances of A and not class objects. They don't have the protection A has and you can assign using a1.__dict__['abc'] = 'xyz'

于 2012-05-08T12:21:23.673 回答