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

时间:2019-11-25 14:05:46

标签: python python-3.x multiple-inheritance super

假设我们定义了两个类:

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

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

现在,我们要定义一个继承自CA的第三类B

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()

1 个答案:

答案 0 :(得分:1)

您没有指定您是Python 2还是Python 3,这很重要,我们将看到。但是无论哪种方式,如果您将在派生类中使用super()来初始化基类,则基类也必须使用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(类必须是新式类)或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__()