+ のオーバーロード
オーバーロードできるのは比較演算子だけではありません。Python のクラスは、+ や - といった算術演算子に対しても独自の機能を実装できます。ここでは、Storage クラスに対して + 演算子をオーバーロードする練習を行います。
この演習はコースの一部です
Python 中級オブジェクト指向プログラミング
演習の手順
Storageクラスで+演算子をオーバーロードするマジックメソッドを定義します。- 2 つのオブジェクトの
capacityの合計と同じcapacityを持つ、新しいStorageオブジェクトtotal_storageを作成します。 onboard_storageとexternal_driveを加算してtotal_storageを作成し、total_storageのcapacityを出力します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
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.____)