繼承(inheritance)
是物件導向最重要的概念之一,它可以讓子物件擁有父物件的屬性及方法,並且擁有屬於自己專屬的屬性或方法,定義類別本身就是一個抽象化(abstraction)
的過程,我們必須抽象描述出這個類別該有的屬性或方法
舉個例子,一個車子的類別(父類別)擁有一些共通的屬性例如有輪子、車門、車窗、引擎
class Car:
def __init__(self, wheel_number, door_number, power):
self.wheel_number = wheel_number
self.door_number = door_number
self.power = power
然而車子也有分為好幾種不同類別(子類別),例如我們定義**電動車(子類別)**繼承了車子類別,電動車類別此時就有了車子的屬性,甚至可以添加自己專有的屬性或方法,如下列程式碼
class EletricCar(Car):
def __init__(self, wheel_number, door_number, power, brand):
super(EletricCar, self).__init__(wheel_number, door_number, power)
self.brand = brand
def get_spec(self):
print(f"wheel_number: {self.wheel_number}")
print(f"door_number: {self.door_number}")
print(f"door_number: {self.door_number}")
print(f"brand: {self.brand}")
c = EletricCar(4,5,"Motor","Tesla")
super()內建函數是繼承時用來呼叫父類別的方法,語法為super(type[, object-or-type])