Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my instance variable not in __dict__?

Tags:

python

If I create a class A as follows:

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

Inspecting the __dict__ member looks like {'name': 'A'}

If however I create a class B:

class B:
    name = 'B'

__dict__ is empty.

What is the difference between the two, and why doesn't name show up in B's __dict__?

like image 235
David Sykes Avatar asked Aug 30 '08 09:08

David Sykes


2 Answers

B.name is a class attribute, not an instance attribute. It shows up in B.__dict__, but not in b = B(); b.__dict__.

The distinction is obscured somewhat because when you access an attribute on an instance, the class dict is a fallback. So in the above example, b.name will give you the value of B.name.

like image 197
Carl Meyer Avatar answered Oct 21 '22 19:10

Carl Meyer


class A:
    def _ _init_ _(self):
        self.name = 'A'
a = A()

Creates an attribute on the object instance a of type A and it can therefore be found in: a.__dict__

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

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

like image 12
Tendayi Mawushe Avatar answered Oct 21 '22 18:10

Tendayi Mawushe