Python抽象类怎么定义_abc模块使用

3次阅读

Python抽象类怎么定义_abc模块使用

python 中定义抽象类,核心是使用 abc 模块(Abstract Base classes),关键在于让类继承 ABC,并用 @abstractmethod 装饰器标记必须由子类实现的方法。

1. 基础写法:继承 ABC + @abstractmethod

抽象类不能直接实例化,只用来被继承。子类若未实现全部抽象方法,实例化时会报错。

示例:

from abc import ABC, abstractmethod <p>class Animal(ABC): @abstractmethod def speak(self): pass</p><pre class="brush:php;toolbar:false;">@abstractmethod def move(self):     pass

下面这行会报错:TypeError: Can’t instantiate abstract class…

a = Animal()

class Dog(Animal): def speak(self): return “Woof!” def move(self): return “Run”

dog = Dog() # ✅ 正常创建 print(dog.speak()) # Woof!

2. 抽象属性和非抽象方法可共存

抽象类里可以有普通方法、类属性、实例属性,甚至带默认实现的方法——只有加了 @abstractmethod 的才强制重写。

立即学习Python免费学习笔记(深入)”;

  • 抽象方法:必须在子类中实现,否则无法实例化
  • 普通方法:可在抽象类中提供通用逻辑,子类可直接调用或重写
  • 抽象属性:用 @Property + @abstractmethod 组合声明(如 @property @abstractmethod

3. 检查是否为抽象类或含未实现方法

可通过 inspect.isabstract() 或查看 __abstractmethods__ 集合判断:

from abc import ABC, abstractmethod import inspect <p>class Shape(ABC): @abstractmethod def area(self): ...</p><p>print(inspect.isabstract(Shape))           # True print(Shape.<strong>abstractmethods</strong>)          # {'area'} print(hasattr(Shape, '<strong>abstractmethods</strong>'))  # True </p>

4. 不强制继承 ABC,但推荐显式声明

技术上,只要类有 @abstractmethod,Python 就会将其视为抽象基类;但不继承 ABC 会导致 ide 提示弱、类型检查不友好,且缺少 ABC 提供的元类保障。

  • ✅ 推荐写法:class MyAbstract(ABC):
  • ❌ 不推荐:class MyAbstract:(即使有 @abstractmethod,行为可能不稳定)

text=ZqhQzanResources