Abstract Base Classes

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

Jake Roach

Data Engineer

Abstract base classes

Abstract base classes สร้าง โครงสร้างพื้นฐาน ให้กับคลาสด้วยการกำหนด abstract methods ที่คลาสลูกทุกตัวต้องนำไปใช้งาน

  • รับประกันพฤติกรรมร่วมกันของกลุ่มคลาส
  • decorator @abstractmethod
  • ออกแบบมาเพื่อสืบทอด ไม่ใช่สร้าง instance โดยตรง
  • ไม่จำเป็นต้องเป็น abstract ทุก method (มี concrete methods ได้)
class School:
    # Do things such as enroll 
    # and add a course
class MiddleSchool:
    # Play an instrument, join a club
    # but must enroll and add courses
class HighSchool:
    # Play a varsity sport, apply
    # for college, but must enroll 
    # and add courses
Object-Oriented Programming ใน Python ระดับกลาง

การสร้าง abstract base class

from abc import ABC, abstractmethod

# Create an abstract base class that inherits # from ABC class School(ABC): @abstractmethod def enroll(self): # This method must be implemented # in classes that inherit from it pass
# Concrete methods are inherited def graduate(self): print("Congrats on graduating!")
  • สืบทอดจากคลาส ABC ใน module abc
  • pass
  • คลาสที่สืบทอดจาก School ต้องนำ method enroll() ไปใช้งาน
  • สามารถเพิ่ม concrete methods ได้เช่นกัน
Object-Oriented Programming ใน Python ระดับกลาง

การนำ abstract base classes ไปใช้งาน

class HighSchool(School):
    def enroll(self):
        print("Welcome to high school!")

# Create an instance of HighSchool
high_school = HighSchool()
high_school.enroll()
Welcome to high school!
high_school.graduate()
Congrats on graduating!
  • HighSchool ต้อง กำหนด method enroll()
  • เกิด TypeError หากไม่ได้กำหนด enroll()
  • HighSchool สืบทอด method graduate() มาด้วย
Object-Oriented Programming ใน Python ระดับกลาง

Abstract methods หลายตัว

class School(ABC):
    @abstractmethod
    def enroll(self):
        pass

    @abstractmethod
    def add_course(self, course_name):
        pass

    def graduate(self):
        print("Congrats on graduating!")

  • มี abstract methods สองตัว ได้แก่ enroll() และ add_course()
class HighSchool(School):
    def __init__(self):
        self.courses = []

    # Implementing abstract method
    def enroll(self):
        print("Welcome to high school!")

    # Implementing abstract method
    def add_course(self, course_name):
        self.courses.append(course_name)
        print(f"You enrolled in {course_name}")

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

มาฝึกกันเถอะ!

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

Preparing Video For Download...