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

การสร้าง 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}!")
แก้ไขและรันโค้ด