Why is my instance variable not in __dict__?

If I create class A as follows:

 class A: def __init__(self): self.name = 'A' 

Checking the __dict__ element looks like {'name': 'A'}

If I create class B :

 class B: name = 'B' 

__dict__ empty.

What is the difference between them and why is not name displayed in B __dict__ ?

+30
python
Aug 30 '08 at 9:12
source share
2 answers

B.name is a class attribute, not an instance attribute. It maps to B.__dict__ , but not to b = B(); b.__dict__ b = B(); b.__dict__ .

The difference is somewhat obscured because when you access the instance attribute, the dict class is fallback. So in the above example, B.name will give you the value B.name .

+42
Aug 30 '08 at 9:33
source share
 class A: def _ _init_ _(self): self.name = 'A' a = A() 

Creates an instance attribute of an object a of type A, so it can be found in: a.__dict__

 class B: name = 'B' b = B() 

Creates an attribute of class B, and the attribute can be found in B.__dict__ , alternatively, if you have an instance b of type B, you can see class level attributes in b.__class__.__dict__

+11
Sep 02 '08 at 15:12
source share



All Articles