开始使用免费开始使用

多级继承

您已经亲自实践了单继承和多继承。本练习中,您将通过构建新版 Smartphone 类来实现多级继承。

为帮助您开始,下面已提供 ComputerTablet 类。需要特别注意的是,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)

本练习是课程的一部分

Python 面向对象编程进阶

查看课程

练习说明

  • 定义一个继承自 TabletSmartphone 类,调用父类构造函数,并定义实例属性 phone_number
  • 创建 send_text 方法,从 Smartphonephone_numberrecipient 发送文本 message
  • 实例化名为 personal_phoneSmartphone 对象并调用其 .browse_internet() 方法;卸载 Weather 应用;通过短信向 Chuck 发送消息 Time for a new mission!

交互式实操练习

通过完成这段示例代码来试试这个练习。

# 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")
编辑并运行代码