เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การสืบทอดแบบหลายระดับ

ได้ลองทำการสืบทอดทั้งแบบเดี่ยวและแบบหลายคลาสมาแล้ว ในแบบฝึกหัดนี้ จะนำการสืบทอดแบบ หลายระดับ มาใช้ โดยสร้างคลาส 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")
แก้ไขและรันโค้ด