使用super()时未调用Python多继承构造函数 [英] Python multiple inheritance constructor not called when using super()
本文介绍了使用super()时未调用Python多继承构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下代码:
class A(object):
def __init__(self):
pass
class B(object):
def __init__(self):
self.something = 'blue'
def get_something(self):
return self.something
class C(A,B):
def __init__(self):
super().__init__()
print(self.get_something())
然后执行:
c = C()
结果如下:
AttributeError: 'C' object has no attribute 'something'
我认为这是由于在使用super()时未调用B的构造函数而发生的.有没有办法使用Python 3实现正确的行为?
I suppose this happens due to the constructor of B not being called when using super(). Is there a way to achieve the correct behavior with Python 3?
推荐答案
如果超类的子类使用超类,则它们应使用super.如果将super().__init__()
行添加到A和B中,则您的示例应该可以再次使用.
Superclasses should use super if their subclasses do. If you add the super().__init__()
line into A and B your example should work again.
检查C的方法解析顺序:
Check the method resolution order of C:
>>> C.mro()
[__main__.C, __main__.A, __main__.B, builtins.object]
本文应该可以解决问题.
This article should clear things up.
这篇关于使用super()时未调用Python多继承构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文