

新闻资讯
技术学院Python抽象类需继承ABC、含@abstractmethod方法且不可实例化,强制子类实现抽象方法,支持抽象属性和多继承,兼具接口契约与默认行为。
Python 中的抽象类不是用来实例化的,而是为子类提供统一接口和强制约束。核心在于 abc 模块(Abstract Base Classes),配合 @abstractmethod 装饰器,让“未实现方法”的错误在实例化时就暴露,而不是运行到调用才报错。
一个类要成为真正的抽象类,需同时满足:
示例:
from abc import ABC, abstractmethodclass Shape(ABC): @abstractmethod def area(self): pass
s = Shape() # ❌ Type
Error: Can't instantiate abstract class
立即学习“Python免费学习笔记(深入)”;
只有被 @abstractmethod 标记的方法,子类才必须实现。抽象类中也可以有普通方法、类方法、静态方法,它们可被子类直接继承使用,无需重写。
例如:
class Shape(ABC):
def describe(self): # ✅ 普通方法,子类自动继承
return "This is a shape"
@classmethod
def version(cls): # ✅ 类方法,也可被继承
return "1.0"
@abstractmethod
def area(self): # ❗必须在子类中实现
passclass Circle(Shape):
def init(self, r):
self.r = r
def area(self): # ✅ 必须实现,否则实例化时报错
return 3.14 * self.r ** 2
接口规范的本质:协议比继承更灵活
Python 更推崇“鸭子类型”——只要对象有 area() 方法,就能当 Shape 用。但抽象类提供了显式契约,尤其适合团队协作或大型项目:
注意:Python 没有 interface 关键字,抽象类就是事实上的接口载体,只是它允许带默认行为。
除了方法,还能定义抽象属性(用 @property + @abstractmethod):
class Shape(ABC):
@property
@abstractmethod
def name(self) -> str:
...
class Rectangle(Shape):
@property
def name(self):
return "Rectangle"
也支持多继承抽象类(只要所有抽象方法都被实现):
class Drawable(ABC):
@abstractmethod
def draw(self):
...
class Resizable(ABC):
@abstractmethod
def resize(self, factor):
...
class ScalableRect(Rectangle, Drawable, Resizable):
def draw(self):
print("Drawing rect")
def resize(self, factor):
self.width = factor
self.height = factor