開始使用免費開始

多載等號運算(Equality Overloading)

當你用 == 比較自訂類別的兩個物件時,Python 預設只會比較這兩個物件所指向的記憶體位置,而不是物件裡的資料。若要改寫這個行為,可以在類別中實作一個特殊方法,接受兩個參數(要比較的兩個物件),並回傳 TrueFalse。當兩個物件被比較時,這個方法會被隱式呼叫。

上一章的 BankAccount 類別已在 script.py 中提供。它有兩個屬性 balancenumber,以及一個 withdraw() 方法。兩個餘額相同的帳戶不一定是同一個帳戶,但銀行帳戶通常有「帳戶號碼」,而帳戶號碼相同的兩個帳戶應該被視為同一個。

本練習屬於課程

Python 物件導向程式設計入門

檢視課程

練習說明

  • 修改 __init__() 方法,新增一個名為 number 的參數,並初始化新的 number 屬性。
  • 定義一個方法,用來比較兩個物件的 number 屬性是否相等。

動手互動練習

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

class BankAccount:
  # Modify to initialize a number attribute
  def __init__(self, ____, balance=0):
    self.balance = balance
    ____
      
  def withdraw(self, amount):
    self.balance -= amount 
    
  # Define __eq__ that returns True if the number attributes are equal 
  def ____(____, ____):
    return ____.number == ____.____   

# Create accounts and compare them       
acct1 = BankAccount(123, 1000)
acct2 = BankAccount(123, 1000)
acct3 = BankAccount(456, 1000)
print(acct1 == acct2)
print(acct1 == acct3)
    
編輯並執行程式碼