Truy cập thuộc tính balance
Trong bài tập này, bạn sẽ luyện cách truy cập thuộc tính balance của lớp BankAccount được cài đặt descriptor bằng decorator @property. Lớp BankAccount đã được tạo sẵn như dưới đây:
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
Bài tập này là một phần của khóa học
Lập trình Hướng đối tượng Nâng cao với Python
Hướng dẫn bài tập
- In ra thuộc tính
balancecủa đối tượngchecking_accountvừa được tạo bằngprint(). - Gán giá trị
balancethành150và in lại thuộc tính đã cập nhật. - Xóa thuộc tính
balancekhỏi đối tượngchecking_account.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
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.____