1 Python 2.7中的繼承 2 在Python 2.7中,繼承語法稍有不同,ElectricCar 類的定義類似於下面這樣: 3 class Car(object): 4 def __init__(self, make, model, year): 5 --snip--
6
7 class ElectricCar(Car): 8 def __init__(self, make, model, year): 9 super(ElectricCar, self).__init__(make, model, year) 10 --snip--
11 函數super() 需要兩個實參:子類名和對象self 。為幫助Python將父類和子類關聯起來,這些實參必不可少。另外,在Python 2.7中使用繼承時,務必在定義父類時在括號內指定object 。 12
13 Python 3中的繼承 14 class Car(): 15 def __init__(self, make, model, year): 16 --snip--
17
18 class ElectricCar(Car): 19 def __init__(self, make, model, year): 20 '''初始化父類的屬性'''
21 super().__init__(make, model, year) 22 --snip--