如何访问Python超级类的属性,例如通过__class __.__ dict__吗? [英] How to access properties of Python super classes e.g. via __class__.__dict__?

查看:109
本文介绍了如何访问Python超级类的属性,例如通过__class __.__ dict__吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取python类的所有属性名称,包括从超类继承的属性?

How can I get all property names of a python class including those properties inherited from super classes?

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继承的名称!"

How can I access properties of a via b? Need: "Give me a list of all property names from b including those inherited from 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也应该起作用.

I want to get results from the first (a), when working with the second (b), but current only can get an empty list. This also should work for another C inherited from B.

推荐答案

您可以使用"dir",也可以遵循"mro"(方法解析顺序,由类上的__mro__属性)-此后一种方法是发现属性的唯一方法,该属性随后会被子类覆盖:

You can either use "dir", or you can follow all the classes that are contained in the tuple returned by "mro" (method resolution order,given by the __mro__ attribute on the class) - this later method is the only way of uncovering attributes that where later overriden by subclasses:

>>> 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)
>>> 

这篇关于如何访问Python超级类的属性,例如通过__class __.__ dict__吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆