7.1 super()方法
既然提到繼承層次,那麼我們談談處理基礎類別中的字段和方法的細節。在Python中有個特別的 方法 super()。這個方法用來在子類別中呼叫基礎類別的方法。
它有三個主要的應用領域:
呼叫父類別的方法:
super()方法允許在子類別中呼叫父類別的方法,而不需要明確指定父類別的名稱。這在處理多重繼承時特別有用,有助於避免在更改類別層次時出錯。
初始化基礎類別:
super()經常在子類別的建構子中使用以呼叫基礎類別的建構子,從而可以在子類別中初始化基礎類別的屬性。
支援多重繼承:
在多重繼承的情況下, super()正確解決方法的調用順序(MRO, Method Resolution Order),這使得它的使用比明確呼叫父類別的方法更推薦。稍後我們會討論這一點。
7.2 基礎類別的建構子
基礎類別的建構子必須明確地被呼叫。似乎這會自動發生,但實際上不是這樣。基礎類別的建構子總是需要明確地被呼叫,因為它們通常需要傳遞特定的參數。
例子:
class Animal:
def __init__(self, type, name):
self.type = type
self.name = name
class Dog(Animal):
def __init__(self, name):
super().__init__("狗狗", name) # 呼叫基礎類別的建構子
class Cat(Animal):
def __init__(self, name):
super().__init__("貓咪", name) # 呼叫基礎類別的建構子
# 創建 Dog 實例
dog = Dog("Buddy")
print(dog)
在這個例子中,基礎類別 (Animal) 的建構子有兩個參數:動物的類型和名字。而繼承類別只有一個—只有名字。
正是在類別 Dog 和 Cat 的建構子中決定該傳遞什麼給基礎類別的建構子—動物類型名稱「狗狗」和「貓咪」。
所以:
- 必須在繼承類別的建構子中呼叫基礎類別的建構子。
- 為此需要使用
super()方法。 - 無需單獨傳遞參數
self— Python 會在呼叫方法時自動填入。
7.3 使用 super()方法
在Python中,super()方法不僅可以在建構子中使用,還可以在類別的其他方法中用於呼叫父類別的方法。當需要擴展或修改父類別中定義的方法的行為時,這可能會很有用。
讓我們來看幾個例子:
在子方法中呼叫父類別的方法
在這個例子中, Dog類中的 speak()方法首先使用 super()呼叫 Animal類中的 speak()方法,然後添加自己的行為。
class Animal:
def speak(self):
return "某種一般的動物聲音"
class Dog(Animal):
def speak(self):
parent_speech = super().speak() # 呼叫父類別的方法
return f"{parent_speech} 而狗會汪汪叫!"
dog = Dog()
print(dog.speak()) # 輸出:某種一般的動物聲音 而狗會汪汪叫!
在修改狀態的方法中呼叫父類別的方法
在這個例子中, Dog類中的 check_health()方法呼叫 Animal類中的 check_health()方法添加額外的檢查。
class Animal:
def check_health(self):
return "動物是健康的"
class Dog(Animal):
def check_health(self):
parent_check = super().check_health() # 呼叫父類別的方法
return f"{parent_check}. 狗需要散步!"
dog = Dog()
print(dog.check_health()) # 輸出:動物是健康的。 狗需要散步!
在修改狀態的方法中呼叫父類別的方法
在這個例子中, SavingsAccount類的 withdraw() 方法首先檢查是否超過提款限額,如果沒有,則調用 BankAccount類的 withdraw()方法來執行操作。
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
return f"提取 {amount}。 新餘額:{self.balance}"
return "資金不足"
class SavingsAccount(BankAccount):
def withdraw(self, amount):
if amount > 1000:
return "超出提款限額"
return super().withdraw(amount) # 呼叫父類別的方法
savings = SavingsAccount(1500)
print(savings.withdraw(500)) # 輸出:提取 500。 新餘額:1000
print(savings.withdraw(1500)) # 輸出:超出提款限額
GO TO FULL VERSION