如何在多重继承中使用`super`?

How to use `super` in multiple inheritance?

假设我们定义了两个 classes:

class A():
    def __init__(self):
        self.a = 0

class B():
    def __init__(self):
        self.b = 0

现在,我们要定义继承自 AB 的第三个 class C:

class C(A, B):
    def __init__(self):
        A.__init__(self)   # how to do this using super()
        B.__init__(self)   # how to do this using super()

您没有说明您是 Python 2 还是 Python 3,这很重要,我们将看到。但无论哪种方式,如果您将在派生 class 中使用 super() 来初始化基础 classes,那么基础 classes 也必须使用 super() .所以,

对于Python 3:

class A():
    def __init__(self):
        super().__init__()
        self.a = 0

class B():
    def __init__(self):
        super().__init__()
        self.b = 0

class C(A, B):
    def __init__(self):
        super().__init__()

对于Python 2(其中classes必须是新式classes)或Python 3

class A(object):
    def __init__(self):
        super(A, self).__init__()
        self.a = 0

class B(object):
    def __init__(self):
        super(B, self).__init__()
        self.b = 0

class C(A, B):
    def __init__(self):
        super(C, self).__init__()