Dostęp do atrybutu balance
W tym ćwiczeniu przećwiczysz dostęp do atrybutu balance klasy BankAccount, która implementuje deskryptor za pomocą dekoratora @property. Klasa BankAccount została już przygotowana, jak pokazano poniżej:
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
To ćwiczenie jest częścią kursu
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany
Instrukcje do ćwiczenia
- Wyświetl atrybut
balancenowo utworzonego obiektuchecking_accountza pomocąprint(). - Ustaw wartość
balancena150, a następnie ponownie wyświetl zaktualizowany atrybut. - Usuń atrybut
balancez obiektuchecking_account.
Interaktywne ćwiczenie praktyczne
Spróbuj tego ćwiczenia, uzupełniając ten przykładowy kod.
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.____