2016-08-13 30 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