存取不存在的屬性
有時你會嘗試存取某個物件命名空間中不存在的屬性。通常此時會拋出 AttributeError。在本練習中,你將使用 Python 的其中一個魔術方法來練習處理這種情況。加油!
本練習屬於課程
Python 物件導向程式設計進階
練習說明
- 定義一個方法,當參照到不在
BankAccount命名空間中的屬性時會被執行;此方法應接受參數self與name。 - 在該魔術方法中加入邏輯,列印訊息,建議應為此物件設定所參照的屬性。
- 建立一個
BankAccount類別的物件,並嘗試存取routing_number屬性;觀察輸出。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
class BankAccount:
def __init__(self, account_number):
self.account_number = account_number
# Define a magic method to handle references to attribute
# not in an object's namespace
def ____(____, ____):
# Output a message to instruct further action
print(f"""{____} is not defined in BankAccount object.
Please define this attribute if needed.""")
# Create a BankAccount object, reference routing_number
checking_account = ____("123456")
____.____