Začněte nyníZačněte zdarma

Přístup k atributu balance

V tomto cvičení si procvičíš přístup k atributu balance třídy BankAccount, která implementuje deskriptor pomocí dekorátoru @property. Třída BankAccount je pro tebe již připravená, jak je znázorněno níže:

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

Toto cvičení je součástí kurzu

Intermediate Object-Oriented Programming in Python

Zobrazit kurz

Pokyny k cvičení

  • Vypiš pomocí print() hodnotu atributu balance nově vytvořeného objektu checking_account.
  • Nastav hodnotu balance na 150 a znovu vypiš aktualizovaný atribut.
  • Odstraň atribut balance z objektu checking_account.

Interaktivní cvičení na vyzkoušení si v praxi

Vyzkoušejte si toto cvičení dokončením tohoto ukázkového kódu.

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.____
Upravit a spustit kód