Toegang tot het attribuut balance
In deze oefening ga je het attribuut balance benaderen van een BankAccount-klasse die een descriptor implementeert met de decorator @property. De BankAccount-klasse is voor je aangemaakt, zoals hieronder getoond:
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
Deze oefening maakt deel uit van de cursus
Gevorderde objectgeoriënteerde programmering in Python
Oefeninstructies
- Print het attribuut
balancevan het nieuw aangemaakte objectchecking_accountmetprint(). - Stel de waarde van
balancein op150en print daarna opnieuw het bijgewerkte attribuut. - Verwijder het attribuut
balancevan het objectchecking_account.
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
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.____