python中的抽象类

0 阅读2分钟

抽象类(Abstract Base Class)

抽象类是不能直接创建实例的类,用来规定子类必须实现哪些方法。

Python 用 abc 模块实现,核心是两个东西:

  • ABC:继承它,就表示这是抽象类
  • @abstractmethod:标记「子类必须实现」的方法
from abc import ABC, abstractmethod

class Animal(ABC):  # 继承 ABC,表示这是一个抽象类
    @abstractmethod
    def speak(self):
        """子类必须实现这个方法"""
        pass

# animal = Animal()  # TypeError: 不能实例化抽象类

class Dog(Animal):
    def speak(self):  # 必须实现抽象方法
        print("Woof!")

dog = Dog()
dog.speak()  # Woof!

定义抽象类

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        """计算面积"""
        pass

    @abstractmethod
    def perimeter(self):
        """计算周长"""
        pass

    def describe(self):
        """普通方法,子类可直接使用"""
        print(f"这是一个图形,面积: {self.area()}, 周长: {self.perimeter()}")

要点:

  • 继承 ABC → 抽象类
  • @abstractmethod 标记的方法 → 子类必须实现
  • 可以同时有普通方法(有默认实现)
  • 抽象类不能被实例化

抽象属性

方法之外,属性也可以要求子类必须提供:

from abc import ABC, abstractmethod

class Employee(ABC):
    @property
    @abstractmethod
    def salary(self):
        """子类必须实现 salary 属性"""
        pass

class FullTimeEmployee(Employee):
    def __init__(self, monthly_salary):
        self._monthly_salary = monthly_salary

    @property
    def salary(self):
        return self._monthly_salary

emp = FullTimeEmployee(10000)
print(emp.salary)  # 10000
  • @abstractmethod:标记这个方法/属性必须被子类实现
  • @property:让子类实现后可以用 emp.salary 而不是 emp.salary() 来访问,像属性一样使用

两者组合起来就是:强制子类提供一个"属性",且调用方式像属性而非方法。

注意: @property 要写在 @abstractmethod 上面,顺序不能颠倒。


子类必须实现全部抽象方法

少实现一个,子类本身仍是抽象类,照样不能实例化:

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    # 忘记实现 perimeter 方法

# rect = Rectangle(3, 4)  # TypeError: 不能实例化抽象类 Rectangle