Mengakses atribut balance
Pada latihan ini, Anda akan berlatih mengakses atribut balance dari kelas BankAccount yang mengimplementasikan descriptor menggunakan dekorator @property. Kelas BankAccount telah dibuat untuk Anda seperti berikut:
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
Latihan ini adalah bagian dari kursus
Pemrograman Berorientasi Objek Tingkat Menengah di Python
Petunjuk latihan
- Keluarkan atribut
balancedari objekchecking_accountyang baru dibuat menggunakanprint(). - Tetapkan nilai
balancemenjadi150lalu keluarkan kembali atribut yang telah diperbarui. - Hapus atribut
balancedari objekchecking_account.
Latihan interaktif praktis
Cobalah latihan ini dengan menyelesaikan kode contoh berikut.
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.____