python - 如何访问 Python 父类(super class)的属性,例如通过 __class__.__dict__?

标签 python reflection properties parent introspection

如何获取 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/

相关文章:

python - 使用flask创建Json对象

java - sun.reflect.CallerSensitive 注释是什么意思?

Java Bean : Overglorified Associative Arrays?

xcode - 合成错误“属性实现声明缺少上下文”

python - 如何在 Elasticsearch 中启用滚动功能

python - 以编程方式阻止特定文件(.txt 扩展名)的打印请求?

java - Ant、jvmarg、系统属性和引号

抽象基类中的 c# 属性

python - 在 numpy 中一次将函数应用于 3 个元素

java - 如何在Java中从C文件中获取方法和参数的名称?