Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`__dict__` of classes in Python

Tags:

python

class

Code goes first,

#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})

Question

1.what is dict_proxy and why use it?

2.A.__dict__ contains an attr -- '__dict': <attribute '__dict__' of 'A' objects>. What is this? Is it for a1 and a2? But objects of A have their own __dict__, don't they?

like image 562
Alcott Avatar asked Dec 13 '25 15:12

Alcott


2 Answers

For your fist question I quote from 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.
like image 87
Niek de Klein Avatar answered Dec 15 '25 05:12

Niek de Klein


For your second question:

>>> 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})

Does this answer your question?

If not, dive deeper: https://stackoverflow.com/a/4877655/1324545

like image 33
ch3ka Avatar answered Dec 15 '25 03:12

ch3ka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!