始める無料で始める

多段継承

単一継承と多重継承の両方に触れてきました。この演習では、Smartphone クラスの新しいバージョンを作成し、多段継承 を実装します。

取りかかりやすいように、ComputerTablet クラスはすでに定義済みで下に用意してあります。重要な点として、TabletComputer クラスを継承しています。頑張ってください!

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 中級オブジェクト指向プログラミング

コースを見る

演習の手順

  • Tablet を継承する Smartphone クラスを定義し、親のコンストラクタを呼び出して、インスタンス属性 phone_number を定義してください。
  • Smartphonephone_number から、recipient にテキスト message を送る send_text メソッドを作成してください。
  • personal_phone という Smartphone オブジェクトを作成し、その .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")
コードを編集して実行