Question

I would like to understand the following situation:

>>> class Test:
...     a = 1
...
>>> x = Test()
>>> x.__dict__
{}
>>> x.a
1
>>> x.__dict__
{}
>>> x.a = 1
>>> x.__dict__
{'a': 1}

Where is the a attribute stored at the beginning and how come it becomes visible in the __dict__ only after assignment?

Was it helpful?

Solution

They are stored on the class itself:

>>> class Test:
...     a = 1
... 
>>> Test.__dict__
{'a': 1, '__module__': '__main__', '__doc__': None}

Python looks first at the instance attributes, then to the class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top