抽象基类

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 面向对象编程进阶

Passons à la pratique !

Python 面向对象编程进阶

Preparing Video For Download...