開始使用免費開始

多載 +

可被多載的並不只有比較運算子。Python 的類別也能為像是 +- 這類算術運算子實作自訂功能。在這個例子中,你將練習為 Storage 類別多載 + 運算子。

本練習屬於課程

Python 物件導向程式設計進階

檢視課程

練習說明

  • Storage 類別定義一個魔術方法,以多載 + 運算子。
  • 建立一個名為 total_storage 的新 Storage 物件,其 capacity 等於兩個物件的 capacity 加總。
  • 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.____)
  
編輯並執行程式碼