การสร้าง Abstract Base Class
Abstract base class เป็นวิธีที่ยอดเยี่ยมในการสร้าง "พิมพ์เขียว" สำหรับกลุ่มคลาสที่มีลักษณะคล้ายกัน ในแบบฝึกหัดนี้ จะได้สร้าง abstract base class ชื่อ Company ที่มีทั้ง abstract method และ concrete method โชคดีนะ!
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Object-Oriented Programming ใน Python ระดับกลาง
คำแนะนำการฝึกหัด
- นำเข้า
ABCและabstractmethodจากโมดูลabc - สร้าง abstract base class ชื่อ
Companyที่สืบทอดจากABC - กำหนด abstract method ชื่อ
create_budget()โดยใช้passแทนการเขียนลอจิก - สร้าง concrete method ชื่อ
hire_employee()
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Import the ABC class and abstractmethod decorator from abc
from abc import ____, ____
# Define an abstract base class called Company
class ____(____):
# Create an abstract method called create_budget()
____
def ____(self):
____
# Create a concrete method with name hire_employee()
def ____(self, name):
print(f"Welcome to the team, {name}!")