2013-10-22 36 views
1
class Test(): 
    test1 = 1 
    def __init__(self): 
     self.test2 = 2 

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

爲什麼我在__dict__字典中看不到test1屬性?如何獲得課堂中的所有屬性?

+1

因爲'test1'是在類字典。嘗試'輸入(r).__ dict__'。通過嘗試'dir(r)'來獲得所有的屬性 – GP89

回答

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>} 
>>>