質問

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?

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top