2012-03-03 65 views
0

是否有通過類名和實例獲取類的屬性的通用方法?獲取類的屬性

class A: 
    def __init__(self): 
     self.prop = 1 

a = A() 

for attr, value in a.__dict__.items(): 
    print(attr, value) # prop, 1 

class A: 
    def __init__(self): 
     self.prop = 1 

for attr, value in A.__dict__.items(): 
    print(attr, value) 
    #__dict__, __doc__, __init__, __module__, __weakref__ 

爲什麼最後一個例子返回dir attibutes爲何結果不同?

+0

,你會看到什麼給你? – grifaton 2012-03-03 16:53:00

+0

>有沒有通過類名和實例獲取類的屬性的通用方法? <我不明白這個 – warvariuc 2012-03-03 16:57:24

+0

我的意思是如何獲得第二個例子中的類屬性(我想獲得'prop,1')? – Opsa 2012-03-03 17:01:20

回答

1

__dict__, __doc__, __module__, ...實際上出現在一個班級中,即使您沒有創建它們。他們是「內置的」。

因此,dir向您顯示這些屬於正常現象。

__dict__屬性在實例中存儲實例屬性。

class A: 
    def __init__(self): 
     self.prop = 1 

a = A() 
for attr, value in a.__dict__.items(): 
    print(attr, value) 

這顯示了實例屬性。而只有一個實例屬性 - propself.prop = 1

for attr, value in A.__dict__.items(): 

這得到類屬性。 prop已添加到實例,所以它不在這裏。

http://docs.python.org/library/stdtypes.html#special-attributes

從對象獲得所有屬性,包括類屬性,基類的屬性,使用inspect.getmembers

+0

Thx爲您的答案,但告訴如何通過實例獲得'class'屬性? – Opsa 2012-03-03 16:58:24