Python用ABC实现强制接口(需继承+运行时检查),用Protocol实现结构化接口(鸭子类型+静态检查);接口应聚焦行为、小而专注、命名清晰,并配合类型提示。
Python 中没有内置的接口语法,但可以通过抽象基类(ABC)或协议(Protocol)来实现接口设计,核心目标是定义行为契约,让不同类能以统一方式被使用。
适合需要运行时类型检查、明确要求子类必须实现某些方法的场景。继承 abc.ABC,用 @abstractmethod 标记必须实现的方法。
例如:
from abc import ABC, abstractmethodclass PaymentProcessor(ABC): @abstractmethod def charge(self, amount: float) -> bool: pass
@abstractmethod def refund(self, amount: float) -> bool: passclass StripeProcessor(PaymentProcessor): def charge(self, amount: float) -> bool: print(f"Charging ${amount} via Stripe") return True
def refund(self, amount: float) -> bool: print(f"Refunding ${amount} via Stripe") return True
未实现抽象方法的子类实例化时会报错,保障了接口一致性。
从 Python 3.8 起支持,更轻量、不参与继承体系,只关注“有没有对应方法和签名”,符合 Python 的鸭子类型哲学。适合类型提示和静态检查(如 mypy)。
例如:
from typing import Protocolclass Drawable(Protocol): def draw(self) -> None: ... def bounding_box(self) -> tuple[float, float, float, float]: ...
def render(shape: Drawable) -> None: shape.draw() # 类型检查器知道 shape 一定有 draw 方法
class Circle: def draw(self) -> None: print("Drawing a circle")
def bounding_box(self) -> tuple[float, float, float, float]: return (0.0, 0.0, 1.0, 1.0)render(Circle()) # ✅ 无需显式继承,只要结构匹配即可
Serializable、Co
mparable),便于组合和复用save_to(file_path: str) 比 write(obj) 更明确ABC
Protocol