use*_*548 8 python reflection properties introspection parent
如何获取python类的所有属性名称,包括从超类继承的那些属性?
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)]
Run Code Online (Sandbox Code Playgroud)
如何访问via b的属性?需要:"给我一个包含b 中所有属性名称的列表,包括那些从...继承的属性名称."
>>> [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]
[]
Run Code Online (Sandbox Code Playgroud)
我想从第一个(a)获得结果,当使用第二个(b)时,但是当前只能获得一个空列表.这也适用于继承自B的另一个C.
您可以使用dir()
:
for attr_name in dir(B):
attr = getattr(B, attr_name)
if isinstance(attr, property):
print attr
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1803 次 |
最近记录: |