ComenzarEmpieza gratis

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

Este ejercicio forma parte del curso

Intermediate Object-Oriented Programming in Python

Ver curso

Instrucciones del ejercicio

  • Output the balance attribute of the newly-created checking_account object using print().
  • Set the value of balance to 150 and again output the updated attribute.
  • Delete the balance attribute from the checking_account object.

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

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.____
Editar y ejecutar código