IniziaInizia gratis

Accedere all'attributo balance

In questo esercizio, metterai in pratica l'accesso all'attributo balance di una classe BankAccount che ha implementato un descriptor usando il decorator @property. La classe BankAccount è già stata creata per te, come mostrato qui sotto:

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

Questo esercizio fa parte del corso

Programmazione a oggetti intermedia in Python

Visualizza il corso

Istruzioni dell'esercizio

  • Stampa l'attributo balance del nuovo oggetto checking_account usando print().
  • Imposta il valore di balance a 150 e stampa di nuovo l'attributo aggiornato.
  • Elimina l'attributo balance dall'oggetto checking_account.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

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.____
Modifica ed esegui il codice