使用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实现正确的行为?
解决方法:
如果超类的子类使用超类,则应使用超类.如果将super().__ init __()行添加到A和B中,则您的示例应该可以再次使用.
检查C的方法解析顺序:
>>> C.mro()
[__main__.C, __main__.A, __main__.B, builtins.object]
This article应该可以解决问题.
标签:python,python-3-x,oop,inheritance,multiple-inheritance 来源: https://codeday.me/bug/20191011/1895776.html