抽象基底類別

Python 物件導向程式設計進階

Jake Roach

Data Engineer

抽象基底類別

抽象基底類別透過定義「必須由所有子類別實作」的「抽象方法」,為類別建立藍圖。

  • 確保一組類別有共同行為
  • @abstractmethod 修飾器
  • 用來被繼承,不用來實例化
  • 不必所有方法都抽象(可有具體方法)
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
Python 物件導向程式設計進階

建立抽象基底類別

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 模組的 ABC 類別繼承
  • pass
  • 任何繼承 School 的類別都必須實作 enroll() 方法
  • 也可定義具體方法
Python 物件導向程式設計進階

實作抽象基底類別

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 必須定義 enroll() 方法
  • 若未定義 enroll() 會拋出 TypeError
  • HighSchool 會繼承 graduate() 方法
Python 物件導向程式設計進階

多個抽象方法

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

    @abstractmethod
    def add_course(self, course_name):
        pass

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

  • 兩個抽象方法: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}")

Python 物件導向程式設計進階

一起來練習吧!

Python 物件導向程式設計進階

Preparing Video For Download...