存取 balance 屬性
在這個練習中,你將練習存取 BankAccount 類別的 balance 屬性。這個類別使用 @property 裝飾器實作了一個描述器(descriptor)。BankAccount 類別已經為你建立,如下所示:
class BankAccount:
def __init__(self, balance):
self.balance = balance
@property
def balance(self):
return f"${round(self._balance, 2)}"
@balance.setter
def balance(self, new_balance):
if new_balance > 0:
self._balance = new_balance
@balance.deleter
def balance(self):
print("Deleting the 'balance' attribute")
del self._balance
本練習屬於課程
Python 物件導向程式設計進階
練習說明
- 使用
print()輸出新建立的checking_account物件的balance屬性。 - 將
balance設為150,再輸出更新後的屬性。 - 從
checking_account物件中刪除balance屬性。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
checking_account = BankAccount(100)
# Output the balance of the checking_account object
print(____.____)
# Set the balance to 150, output the new balance
____.____ = ____
print(____.____)
# Delete the balance attribute, attempt to print the balance
____ checking_account.____