如何获取 python 类的所有属性名称包括那些从父类(super class)继承的属性?
class A(object):
def getX(self):
return "X"
x = property(getX)
a = A()
a.x
'X'
class B(A):
y = 10
b = B()
b.x
'X'
a.__class__.__dict__.items()
[('__module__', '__main__'), ('getX', <function getX at 0xf05500>), ('__dict__', <attribute '__dict__' of 'A' objects>), ('x', <property object at 0x114bba8>), ('__weakref__', <attribute '__weakref__' of 'A' objects>), ('__doc__', None)]
b.__class__.__dict__.items()
[('y', 10), ('__module__', '__main__'), ('__doc__', None)]
如何通过 b 访问 a 的属性? 需要:“给我一份来自 b 的所有属性 名称的列表,包括那些从 a 继承的!”
>>> [q for q in a.__class__.__dict__.items() if type(q[1]) == property]
[('x', <property object at 0x114bba8>)]
>>> [q for q in b.__class__.__dict__.items() if type(q[1]) == property]
[]
我想在使用第二个 (b) 时从第一个 (a) 获得结果,但当前只能获得一个空列表。这也适用于从 B 继承的另一个 C。
最佳答案
你可以使用dir()
:
for attr_name in dir(B):
attr = getattr(B, attr_name)
if isinstance(attr, property):
print attr
关于python - 如何访问 Python 父类(super class)的属性,例如通过 __class__.__dict__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9377819/