多層繼承
你已經實作過單一與多重繼承。這個練習要你透過建立新版的 Smartphone 類別來實作「多層」繼承。
為了幫助你起步,下面已提供定義好的 Computer 與 Tablet 類別。需要特別注意的是,Tablet 是繼承自 Computer 類別。加油!
class Computer:
def __init__(self, brand):
self.brand = brand
def browse_internet(self):
print(f"Using {self.brand}'s default internet browser.")
class Tablet(Computer):
def __init__(self, brand, apps):
Computer.__init__(self, brand)
self.apps = apps
def uninstall_app(self, app):
if app in self.apps:
self.apps.remove(app)
本練習屬於課程
Python 物件導向程式設計進階
練習說明
- 定義一個繼承自
Tablet的Smartphone類別,呼叫父類別建構函式,並定義實例層級屬性phone_number。 - 建立
send_text方法,從Smartphone的phone_number傳送文字message給recipient。 - 建立名為
personal_phone的Smartphone物件並呼叫其.browse_internet()方法;解除安裝Weather應用程式,並以簡訊將Time for a new mission!傳給 Chuck。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create a Smartphone class that inherits from Tablet
class ____(____):
def __init__(self, brand, apps, phone_number):
____.____(self, ____, ____)
self.phone_number = ____
# Create send_text to send a message to a recipient
def ____(self, message, recipient):
print(f"Sending {____} to {____} from {____.____}")
# Create an instance of Smartphone, call methods in each class
____ = Smartphone("Macrosung", ["Weather", "Camera"], "801-932-7629")
personal_phone.____()
personal_phone.____("____")
personal_phone.____("____", "Chuck")