多載等號運算(Equality Overloading)
當你用 == 比較自訂類別的兩個物件時,Python 預設只會比較這兩個物件所指向的記憶體位置,而不是物件裡的資料。若要改寫這個行為,可以在類別中實作一個特殊方法,接受兩個參數(要比較的兩個物件),並回傳 True 或 False。當兩個物件被比較時,這個方法會被隱式呼叫。
上一章的 BankAccount 類別已在 script.py 中提供。它有兩個屬性 balance 和 number,以及一個 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)