多型是物件導向語嚴重要的特性之一,介紹多型前先來介紹下列的名詞:
由於英文很像的關係常常讓我們搞錯差別,我們來看看下面的例子
python中其實是使用預設參數來呈現多載,我們看看下面的例子
當子類別繼承父類別時,覆寫父類別的方法
class Car:
def __init__(self, wheel_number, door_number, power):
self.wheel_number = wheel_number
self.door_number = door_number
self.power = power
def accelerate(self):
print("Normal 0~100 km/hr acceleration: 10 seconds.")
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 accelerate(self):
print(f"{self.brand} 0~100 km/hr acceleration: 4 seconds.")
c = EletricCar(4,5,"Motor","Tesla")
c.accelerate()
接續上面的例子,我們再定義一個跑車子類別叫SportCar,然後覆寫父類別的accelerate()方法
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 accelerate(self):
print(f"{self.brand} 0~100 km/hr acceleration: 4 seconds.")
class SportCar(Car):
def __init__(self, wheel_number, door_number, power, brand):
super(SportCar, self).__init__(wheel_number, door_number, power)
self.brand = brand
def accelerate(self):
print(f"{self.brand} 0~100 km/hr acceleration: 2.8 seconds.")
t = EletricCar(4,5,"Motor","Tesla")
s = SportCar(4,2,"Engine","Lamborghini")
t.accelerate()
s.accelerate()
從上述例子中可以看到,當子類別繼承父類別,而子類別覆寫了父類別的方法,繼承替父類別衍伸出許多型態的子類別,不同的子類別呼叫相同名稱的方法,產生不同的實作,就是多型的概念,所以說有了繼承才有多型