假设我们定义了两个类:
class A():
def __init__(self):
self.a = 0
class B():
def __init__(self):
self.b = 0
现在,我们要定义一个继承自C
和A
的第三类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()
答案 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__()