如何通过 __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)]
如何通过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。
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)]
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]
[]
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
dir()
:You can use
dir()
:您可以使用“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: