開始使用免費開始

多載 == 運算子

Python 內建的各種運算子相當好用,特別是在比較類別實例時。建立類別時,可以用魔術方法來改變這些運算子的功能。在這裡,你會多載 == 運算子,用來判斷兩個 Computer 實例是否相等。

本練習屬於課程

Python 物件導向程式設計進階

檢視課程

練習說明

  • 定義一個魔術方法來多載 == 運算子。
  • 在該魔術方法中比較 selfotherdevice_id 屬性,以判斷兩個實例是否相等。
  • 檢查 pre_upgrade_computerpost_upgrade_computer 是否相等,並印出結果。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

class Computer:
  def __init__(self, device_id, storage):
    self.device_id = device_id
    self.storage = storage
  
  # Overload the == operator using a magic method
  def ____(self, other):
    # Return a boolean based on the value of device_id
    ____ self.____ == other.____

pre_upgrade_computer = Computer("Y391Hky6", 256)
post_upgrade_computer = Computer("Y391Hky6", 1024)

# Create two instances of Computer, compare using ==
print(____ == ____)
編輯並執行程式碼