Vra

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 dit nuttig?

Oplossing

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.

Gelisensieer onder: CC-BY-SA met toeskrywing
Nie verbonde aan StackOverflow
scroll top