多載 +
可被多載的並不只有比較運算子。Python 的類別也能為像是 + 與 - 這類算術運算子實作自訂功能。在這個例子中,你將練習為 Storage 類別多載 + 運算子。
本練習屬於課程
Python 物件導向程式設計進階
練習說明
- 為
Storage類別定義一個魔術方法,以多載+運算子。 - 建立一個名為
total_storage的新Storage物件,其capacity等於兩個物件的capacity加總。 - 將
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.____)