方法繼承
繼承之所以強大,是因為它能讓我們在不重寫既有程式碼的情況下重用並自訂功能。當你在子類別中呼叫父類別的方法時,就能重用這些方法中的所有程式碼,讓整體更精簡、好維護。
在這個練習中,你會繼續使用從 Employee 類別繼承而來的 Manager 類別。你將為類別新增資料,並自訂第 1 章的 give_raise() 方法:每次調薪時,依照加給百分比提高經理的加薪幅度。
程式碼窗格中已提供精簡版的 Employee 類別,以及上一個單元開始實作的 Manager 類別雛形。
本練習屬於課程
Python 物件導向程式設計
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
class Employee:
def __init__(self, name, salary=30000):
self.name = name
self.salary = salary
def give_raise(self, amount):
self.salary += amount
class Manager(Employee):
# Add a constructor
def __init__(self, name, ____, ____):
# Call the parent's constructor
____.____(____, ____, salary)
# Assign project attribute
____
def display(self):
print("Manager ", self.name)