访问 balance 属性
在本练习中,您将练习访问 BankAccount 类的 balance 属性。该类使用 @property 装饰器实现了描述符。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.____