使用super()时未调用Python多继承构造函数

使用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.