Python中存储的类的顶级属性在哪里?

时间:2014-05-14 21:29:36

标签: python class scope

我想了解以下情况:

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

a属性存储在开头的哪个位置以及仅在分配后才会在__dict__中显示?

1 个答案:

答案 0 :(得分:4)

它们存储在类本身上:

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

Python首先查看实例属性,然后查看类。