เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การเข้าถึง 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 ของ object checking_account ที่สร้างขึ้นใหม่โดยใช้ print()
  • กำหนดค่าของ balance เป็น 150 แล้วแสดงค่า attribute ที่อัปเดตแล้วอีกครั้ง
  • ลบ attribute balance ออกจาก object checking_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.____
แก้ไขและรันโค้ด