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

การสร้าง formal interface ด้วย ABC

Formal interface ช่วยให้ข้อตกลงระหว่าง interface กับคลาสที่นำไปใช้งานมีความเข้มงวดมากขึ้น แบบฝึกหัดนี้จะฝึกสร้าง formal interface ที่ประกอบด้วย abstract method สองตัว โดยใช้โมดูล abc ซึ่งได้ import คลาส ABC และ decorator abstractmethod จาก abc มาให้แล้ว

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Object-Oriented Programming ใน Python ระดับกลาง

ดูคอร์ส

คำแนะนำการฝึกหัด

  • สร้าง formal interface ชื่อ Product
  • กำหนด purchase() เป็น abstract method โดยรับพารามิเตอร์ self และ quantity แล้วเพิ่มคีย์เวิร์ด pass ไว้ใน method body
  • กำหนด abstract method update_price() โดยรับพารามิเตอร์ self และ new_price

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# Create a Product interface
____ ____(____):
  
  # Define a purchase() abstract method
  ____
  def ____(____, quantity):
    ____
  
  # Create an update_price() abstract method
  ____
  def ____(self, ____):
    ____
แก้ไขและรันโค้ด