Kế thừa đa cấp
Bạn đã thực hành cả kế thừa đơn và kế thừa đa kế. Trong bài này, bạn sẽ triển khai kế thừa đa cấp bằng cách xây dựng một phiên bản mới của lớp Smartphone.
Để bạn bắt đầu thuận lợi, các lớp Computer và Tablet đã được định nghĩa sẵn bên dưới. Lưu ý quan trọng: Tablet kế thừa từ lớp Computer. Chúc bạn may mắn!
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)
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
Hướng dẫn bài tập
- Định nghĩa lớp
Smartphonekế thừa từTablet, gọi constructor của lớp cha và định nghĩa thuộc tính cấp đối tượngphone_number. - Tạo phương thức
send_textđể gửi tin nhắn văn bảnmessageđếnrecipienttừphone_numbercủaSmartphone. - Khởi tạo một đối tượng
Smartphonetênpersonal_phonevà gọi phương thức.browse_internet()của nó; gỡ cài đặt ứng dụngWeather, và gửi tin nhắnTime for a new mission!cho Chuck qua văn bản.
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.
# 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")