簡體   English   中英

使用python中父類的魔術方法__init__初始化子類

[英]Initializing a child class with the magic method __init__ of the parent class in python

我一直在使用python進行在線課程。 一堂課,它似乎已經從a,b,c變成了z。

在上一課中,在子類的init部分中,它似乎采用了父類數組,並將其傳遞給子類的新魔術方法init參數。

class ChildClass(ParentClass):
    def __init__(self, speed, direction):
        ParentClass.__init__(self, [speed, direction])

我在網上找不到任何資源來確認我的解釋。

即使未為self.speed和self.direction分配任何內容,父級是否仍會傳遞其參數?

所述__init__子類的方法ChildClass正在通過它的參數到__init__它的父類的方法ParentClass ,並且父__init__然后方法繼續的對象的初始化。 假設ChildClass.__init__僅包含顯示的代碼,則子方法的唯一要點是使子構造函數的簽名不同於父構造函數的簽名。 如果刪除了ChildClass.__init__則只需將對ChildClass(speed, direction)所有調用更改為ChildClass([speed, direction])即可繼續執行同一操作。

父類就像創建一個有四個輪子的汽車類。

car:
    def__init__(self, wheels):
        self.wheels = 4    

您可以在init函數中定義輪數,也可以在self中定義輪數,但是在init中,輪= x的任何內容都必須位於末尾。

def__init__(self, wheels = 4, color):   # this would fail
def__init__(self, color, wheels = 4): # this would work

現在我們創建一個雪佛蘭(因為福特很爛)

chevy(car):
    def__init__(self, wheels, color = blue):
        self.color = color

    super().__init__(wheels) 

super來自父類,父類中的所有內容都必須在子類中(如果沒有車輪,它將不再是汽車),這將使其崩潰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM