在Python中初始化父類的方法,是在子類繼承的構造函數中調用父類的init
方法。
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
class Student(Person):
def __init__(self,name,age,score):
Person.__init__(self,name,age)
self.score = score
在簡單的繼承體系中,可以使用上述方法,但是對於複雜的繼承,上述初始化父類的方法,會帶來無法預知的行爲錯誤。
影響1:調用順序由子類中的__init__
方法中的順序指定;
影響2:對於菱形繼承,會導致公共的基類的__init__
方法執行多次,從而產生錯誤。
菱形繼承:
因此在Python中總是使用super
函數來初始化父類。
class A(object):
def __init__(self):
print('enter A')
print('leave A')
class B(A):
def __init__(self):
print('enter B')
super().__init__()
print('leave B')
class C(A):
def __init__(self):
print('enter C')
super().__init__()
print('leave C')
class D(B, C):
def __init__(self):
print('enter D')
super().__init__()
print('leave D')