假設我們有一個名為Animal
的父類,它有一個屬性color
,在其構造函數__init__
中被初始化:
class Animal:def __init__(self, color):self.color = color
現在,我們想創建一個Animal
的子類,名為Dog
。Dog
類有自己的屬性name
,但我們也希望它能繼承Animal
類的color
屬性。所以,我們在Dog
類的構造函數中調用super().__init__(color)
:
class Dog(Animal):def __init__(self, color, name):super().__init__(color)self.name = name
在這個例子中,super().__init__(color)
就是在調用Animal
類的構造函數,這樣Dog
類就能繼承Animal
類的color
屬性。如果我們沒有在Dog
類的構造函數中調用super().__init__(color)
,那么Dog
類就不會有color
屬性,因為Animal
類的構造函數沒有被調用。
總而言之super().__init__(root)
的作用就是在子類中調用父類的構造函數,以便子類能繼承父類的屬性和方法。