1
class Test():
test1 = 1
def __init__(self):
self.test2 = 2
r = Test()
print r.__dict__
print getattr(r,'test1')
爲什麼我在__dict__
字典中看不到test1屬性?如何獲得課堂中的所有屬性?
class Test():
test1 = 1
def __init__(self):
self.test2 = 2
r = Test()
print r.__dict__
print getattr(r,'test1')
爲什麼我在__dict__
字典中看不到test1屬性?如何獲得課堂中的所有屬性?
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>}
>>>
因爲'test1'是在類字典。嘗試'輸入(r).__ dict__'。通過嘗試'dir(r)'來獲得所有的屬性 – GP89