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

การสืบทอดหลายชั้น

ในแบบฝึกหัดนี้ จะได้ฝึกนำ multiple inheritance ไปใช้งานจริง โดยการสร้างคลาสใหม่ชื่อ Smartphone

ด้านล่างนี้คือนิยามของคลาส Computer และ Telephone ซึ่งจะถูกใช้ในการสร้างคลาส Smartphone ลองดูทั้งสองคลาสนี้ให้ดีก่อน!

class Computer:
  def __init__(self, brand):
    self.brand = brand

  def browse_internet(self):
    print(f"Using {self.brand}'s default internet browser.")
class Telephone:
  def __init__(self, phone_number):
    self.phone_number = phone_number

  def make_call(self, recipient):
    print(f"Calling {recipient} from {self.phone_number}")

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Object-Oriented Programming ใน Python ระดับกลาง

ดูคอร์ส

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# Define a Smartphone class that inherits from Computer and
# Telephone, and takes parameters brand, phone_number, and 
# music_app
class ____(____, ____):
  def __init__(self, ____, ____, ____):
    # Call the contructor for the Computer and Telephone
    # class, define the music_app instance-level attribute
    ____.__init__(self, brand)
    Telephone.__init__(self, ____)
    self.music_app = ____
แก้ไขและรันโค้ด