在Python中,我可以使用__dict__
获得一个类字段。在这里,我有两个问题:获取派生类的字段
有没有更好的方法来获取字段?因为它只会带来有价值的字段。 如何获得仅存在于类本身而不是基类中的字段?
在Python中,我可以使用__dict__
获得一个类字段。在这里,我有两个问题:获取派生类的字段
有没有更好的方法来获取字段?因为它只会带来有价值的字段。 如何获得仅存在于类本身而不是基类中的字段?
检查:
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('__'))]
我猜你的意思是属性。你有没有尝试* class-name.attribute-name *? – cdarke
是的,属性。我是一个蟒蛇noob,真的没有进入条款。我的目标是制作一个类似于事物的代码生成器。我有从另一个类继承的类。我需要他们的属性和值,而不是基类的属性。 – Doruk