การสร้าง 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, ____):
____