如何访问Python超类的属性,例如,通过?

如何访问Python超类的属性,例如,通过?,python,reflection,properties,parent,introspection,Python,Reflection,Properties,Parent,Introspection,如何获取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 0xf05

如何获取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)]
A类(对象):
def getX(自我):
返回“X”
x=属性(getX)
a=a()
a、 x
“X”
B(A)类:
y=10
b=b()
b、 x
“X”
a、 _uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
[(“模块”、“主”、(“getX”、(“dict”、(“x”、)、(“weakref”、)、(“文档”、(“无”)]
b、 _uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
[('y',10),('u___________________'模块,''u_______'),('u____________
如何通过b访问a的属性? 需要:“给我一份b所有财产名称的清单,包括从a继承的财产名称!”

>>>[q代表a..\uuuuuu类\uuuuuuu.dict\uuuuuuuu.items()中的q,如果类型(q[1])==property]
[('x',)]
>>>[q代表b._类______;条目的q(),如果类型(q[1])==property]
[]
当处理第二个(b)时,我想从第一个(a)中得到结果,但当前只能得到一个空列表。这也适用于从B继承的另一个C。

您可以使用
dir()

您可以使用“dir”,也可以遵循“mro”返回的元组中包含的所有类(方法解析顺序,由类上的
\uuuuuumro\uuuuuuuu
属性给出)-后一种方法是发现随后被子类覆盖的属性的唯一方法:

>>> class A(object):
...    b = 0
... 
>>> class B(A):
...   b = 1
... 
>>> for cls in B.__mro__:
...     for item in cls.__dict__.items():
...         if item[0][:2] != "__":
...            print cls.__name__, item
... 
B ('b', 1)
A ('b', 0)
>>> 

请注意,
y
不是一个属性,它只是一个整数。你想要所有不是函数的类变量吗?如果你关心Python风格(),或者如果你不需要函数调用版本(如果你通过
super()
-
super(…).x='Y'
设置一个属性,你就可以使用
getX
,而不是
getX
。),只需将
属性
用作装饰器,如
@property
定义x(self):返回“x”
。感谢您的评论。我试图创建一个简单的示例,而不是复杂的代码,是的,因此我没有考虑PEP8。我不在乎这个
y
,因为我只需要属性。Ok的副本,我想这对我来说适用于最后的
print attr\u name,attr.\uuu get\uu(b)
。谢谢。谢谢关于python的帮助。de@irc.freenode.net对于导致另一个答案的提示:
对于b中的c.。\uuuuu class\uuuuuuu mro\uuuuuuuuuu:如果issubclass(c,a):对于c中的p,如果类型(q[1])==属性:打印p[0],'=',p[1]。\uuuu获取(b)
@user1156548:我认为没有必要亲自走MRO。当然可以,但为什么要这样做呢?使用mro的工作原理与上面的dir()解决方案类似。如果没有这两者,它就不能工作,因为class.\u dict\u不包含超类的属性。你有什么建议@sven-marnach@user1156548:我建议使用
dir()。
for attr_name in dir(B):
    attr = getattr(B, attr_name)
    if isinstance(attr, property):
        print attr
>>> class A(object):
...    b = 0
... 
>>> class B(A):
...   b = 1
... 
>>> for cls in B.__mro__:
...     for item in cls.__dict__.items():
...         if item[0][:2] != "__":
...            print cls.__name__, item
... 
B ('b', 1)
A ('b', 0)
>>>