Accessing the balance attribute
In this exercise, you'll practice accessing the balance
attribute of a BankAccount
class that's implemented a descriptor using the @property
decorator. The BankAccount
class has been created for you, as shown below:
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
This exercise is part of the course
Intermediate Object-Oriented Programming in Python
Exercise instructions
- Output the
balance
attribute of the newly-createdchecking_account
object usingprint()
. - Set the value of
balance
to150
and again output the updated attribute. - Delete the
balance
attribute from thechecking_account
object.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
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.____