[英]How to get the name of the instance of the parent class from the derived class in Python?
[英]Python: How to access parent class object through derived class instance?
对不起我的愚蠢问题,但是......我想我有这些课:
class A():
msg = 'hehehe'
class B(A):
msg = 'hohoho'
class C(B):
pass
以及B或C的实例。如何通过此实例从父类的对象中获取变量'msg'? 我试过这个:
foo = B()
print super(foo.__class__).msg
但得到消息:“TypeError:super()参数1必须是类型,而不是classobj”。
你其实想要使用
class A(object):
...
...
b = B()
bar = super(b.__class__, b)
print bar.msg
基类必须是新式类(从object
继承)
如果该类是单继承的:
foo = B()
print foo.__class__.__bases__[0].msg
# 'hehehe'
如果该类是多重继承的,那么这个问题没有意义,因为可能有多个类定义了'msg',它们都可能是有意义的。 你最好提供实际的父母(即A.msg
)。 或者,您可以按照@Felix的答案中所述迭代所有直接基础。
不知道你为什么要这样做
>>> class A(object):
... msg = 'hehehe'
...
>>> class B(A):
... msg = 'hohoho'
...
>>> foo=B()
>>> foo.__class__.__mro__[1].msg
'hehehe'
>>>
试试:
class A(object):
msg = 'hehehe'
编辑:
对于'msg'属性,您需要:
foo = B()
bar = super(foo.__class__, foo)
print bar.msg
由于msg
是一个类变量,你可以这样做:
print C.msg # prints hohoho
如果覆盖变量(就像在B
类中那样),则必须找到正确的父类。 请记住,Python支持多重继承 。
但是当您定义类并且现在B
继承自A
您始终可以执行此操作:
class B(A):
msg = 'hohoho'
def get_parent_message(self):
return A.msg
更新:
最可靠的是:
def get_parent_attribute(instance, attribute):
for parent in instance.__class__.__bases__:
if attribute in parent.__dict__:
return parent.__dict__[attribute]
然后:
foo = B()
print get_parent_attribute(foo, 'msg')
#for B() you can use __bases__
print foo.__class__.__bases__[0].msg
但是当有多个基类和/或层次结构的深度不是一个时,这并不容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.