2016-08-13 55 views
0

在Python中,我可以使用__dict__獲得一個類字段。在這裏,我有兩個問題:獲取派生類的字段

有沒有更好的方法來獲取字段?因爲它只會帶來有價值的字段。 如何獲得僅存在於類本身而不是基類中的字段?

+1

我猜你的意思是屬性。你有沒有嘗試* class-name.attribute-name *? – cdarke

+0

是的,屬性。我是一個蟒蛇noob,真的沒有進入條款。我的目標是製作一個類似於事物的代碼生成器。我有從另一個類繼承的類。我需要他們的屬性和值,而不是基類的屬性。 – Doruk

回答

1

檢查:

from types import FunctionType 

class A (object): 
    def test(self): 
     pass 

class B(A): 
    def test12(self): 
     pass 


print([x for x,y in A.__dict__.items() if type(y) == FunctionType]) 

print([x for x,y in B.__dict__.items() if type(y) == FunctionType]) 

對於不是方法的屬性,試試這個:

attributes = [x for x,y in B.__dict__.items() if (type(y) != FunctionType and type != callable)] 

[a for a in attributes if not(a.startswith('__') and a.endswith('__'))] 
+0

此代碼列出了這些功能。我需要屬性。不管怎麼說,還是要謝謝你。 – Doruk

+1

這是幾乎相同的事情。 –

+0

Nidhin,你在你的例子中使用了什麼?我在培訓視頻或類似的東西中看到了這一點,並希望進行實驗。 – LhasaDad