การเข้าถึง attribute balance
ในแบบฝึกหัดนี้ จะได้ฝึกเข้าถึง attribute balance ของ class BankAccount ที่นำ descriptor มาใช้งานผ่าน decorator @property โดย class 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
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Object-Oriented Programming ใน Python ระดับกลาง
คำแนะนำการฝึกหัด
- แสดงค่า attribute
balanceของ objectchecking_accountที่สร้างขึ้นใหม่โดยใช้print() - กำหนดค่าของ
balanceเป็น150แล้วแสดงค่า attribute ที่อัปเดตแล้วอีกครั้ง - ลบ attribute
balanceออกจาก objectchecking_account
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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.____