小编use*_*548的帖子

如何通过__class __.__ dict__访问Python超类的属性?

如何获取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 …
Run Code Online (Sandbox Code Playgroud)

python reflection properties introspection parent

8
推荐指数
1
解决办法
1803
查看次数

标签 统计

introspection ×1

parent ×1

properties ×1

python ×1

reflection ×1