Auf das Attribut balance zugreifen
In dieser Übung übst du den Zugriff auf das Attribut balance einer Klasse BankAccount, die einen Deskriptor mit dem Decorator @property implementiert. Die Klasse BankAccount wurde für dich erstellt, wie unten gezeigt:
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
Diese Übung ist Teil des Kurses
Fortgeschrittene objektorientierte Programmierung in Python
Anleitung zur Übung
- Gib das Attribut
balancedes neu erstellten Objektschecking_accountmitprint()aus. - Setze den Wert von
balanceauf150und gib das aktualisierte Attribut erneut aus. - Lösche das Attribut
balanceaus dem Objektchecking_account.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
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.____