1
class Test():
    test1 = 1
    def __init__(self):
        self.test2 = 2

r = Test()
print r.__dict__
print getattr(r,'test1')

为什么我在__dict__字典中看不到 test1 属性?

4

1 回答 1

5

instance.__dict__包含实例属性,而不是类属性。

要获取类属性,请使用Test.__dict__type(r).__dict__

>>> r = Test()
>>> print r.__dict__
{'test2': 2}
>>> print Test.__dict__
{'test1': 1, '__module__': '__main__', '__doc__': None, '__init__': <function __init__ at 0x000000000282B908>}
>>> print getattr(r,'test1')
1

或者,您可以使用vars

>>> print vars(r)
{'test2': 2}
>>> print vars(Test)
{'test1': 1, '__module__': '__main__', '__doc__': None, '__init__': <function __init__ at 0x000000000282B908>}
>>>
于 2013-10-22T13:49:38.467 回答