多段継承
単一継承と多重継承の両方に触れてきました。この演習では、Smartphone クラスの新しいバージョンを作成し、多段継承 を実装します。
取りかかりやすいように、Computer と Tablet クラスはすでに定義済みで下に用意してあります。重要な点として、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 中級オブジェクト指向プログラミング
演習の手順
Tabletを継承するSmartphoneクラスを定義し、親のコンストラクタを呼び出して、インスタンス属性phone_numberを定義してください。Smartphoneのphone_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")