Bắt đầu ngayBắt đầu miễn phí

Kế thừa đa lớp (Multiple inheritance)

Trong bài tập này, bạn sẽ thực hành triển khai kế thừa đa lớp bằng cách tạo một lớp mới tên là Smartphone.

Bên dưới là định nghĩa các lớp ComputerTelephone, sẽ được dùng khi tạo lớp Smartphone. Hãy xem kỹ cả hai lớp này!

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}")

Bài tập này là một phần của khóa học

Lập trình Hướng đối tượng Nâng cao với Python

Xem khóa học

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

# 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 = ____
Chỉnh sửa và Chạy Mã