第25條 用super初始化父類

在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')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章