考虑以下代码:
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 实现正确的行为?
最佳答案
如果子类使用 super,则父类(super class)应该使用 super。如果将 super().__init__()
行添加到 A 和 B 中,您的示例应该再次运行。
检查C:的方法解析顺序
>>> C.mro()
[__main__.C, __main__.A, __main__.B, builtins.object]
This article应该把事情弄清楚。
关于使用 super() 时不调用 Python 多重继承构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25372653/