始める無料で始める

+ のオーバーロード

オーバーロードできるのは比較演算子だけではありません。Python のクラスは、+- といった算術演算子に対しても独自の機能を実装できます。ここでは、Storage クラスに対して + 演算子をオーバーロードする練習を行います。

この演習はコースの一部です

Python 中級オブジェクト指向プログラミング

コースを見る

演習の手順

  • Storage クラスで + 演算子をオーバーロードするマジックメソッドを定義します。
  • 2 つのオブジェクトの capacity の合計と同じ capacity を持つ、新しい Storage オブジェクト total_storage を作成します。
  • onboard_storageexternal_drive を加算して total_storage を作成し、total_storagecapacity を出力します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

class Storage:
  def __init__(self, capacity):
    self.capacity = capacity
  
  def ____(____, ____):  # Overload the + operator
    # Create a Storage object with the sum of capacity
    return ____(self.____ + other.____)

onboard_storage = Storage(128)
external_drive = Storage(64)

# Add the two Storage objects, show the total capacity
total_storage = ____ + ____
print(total_storage.____)
  
コードを編集して実行