balance 属性へのアクセス
この演習では、@property デコレータを使ったデスクリプタを実装している BankAccount クラスの balance 属性へアクセスする練習をします。以下のとおり、BankAccount クラスは用意されています。
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
この演習はコースの一部です
Python 中級オブジェクト指向プログラミング
演習の手順
- 新しく作成した
checking_accountオブジェクトのbalance属性を、print()を使って出力します。 balanceの値を150に設定し、更新後の属性をもう一度出力します。checking_accountオブジェクトからbalance属性を削除します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
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.____