การสืบทอดแบบหลายระดับ
ได้ลองทำการสืบทอดทั้งแบบเดี่ยวและแบบหลายคลาสมาแล้ว ในแบบฝึกหัดนี้ จะนำการสืบทอดแบบ หลายระดับ มาใช้ โดยสร้างคลาส 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)
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Object-Oriented Programming ใน Python ระดับกลาง
คำแนะนำการฝึกหัด
- กำหนดคลาส
Smartphoneให้สืบทอดจากTabletเรียก constructor ของคลาสแม่ และกำหนด attribute ระดับ instance ชื่อphone_number - สร้างเมธอด
send_textเพื่อส่งข้อความmessageไปยังrecipientโดยใช้phone_numberของSmartphone - สร้าง object
Smartphoneชื่อpersonal_phoneแล้วเรียกเมธอด.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")