

新闻资讯
技术学院本文详解在 python 中为继承自基类的工厂方法(`@classmethod`)添加类型提示的正确方式,解决 mypy 因违反 lsp 而报错的问题,并提供兼容性强、可维护性高的类型安全方案。
在面向对象设计中,使用 @classmethod 实现工厂模式(如 create())十分常见。但当子类扩展参数签名(例如 B.create(a: int, b: int) 相比 A.create(a: int))时,mypy 会报错:Signature of "create" incompatible with supertype "A"。这并非误报——类方法属于类型接口的一部分,调用者可通过 A.create(.
..) 或 B.create(...) 多态调用,因此子类方法签名必须满足父类声明的契约,即遵守里氏替换原则(LSP)。虽然 LSP 原本针对实例行为,但 @classmethod 是类级别的可调用接口,其类型一致性直接影响静态分析的可靠性。
直接修改子类签名以匹配父类(如强行加 b: int = 0)会破坏语义清晰性;而忽略错误(# type: ignore)则丧失类型安全。更优解是在基类中采用“宽松但精确”的类型声明,既允许子类扩展参数,又保持类型系统可验证。
推荐方案:使用 typing_extensions.Concatenate 和 Callable 显式建模“固定首参 + 可变其余参数”:
from __future__ import annotations
import typing_extensions as t
from collections.abc import Callable
class A:
def __init__(self, a: int) -> None:
self.a = a
# 声明:接受至少一个 int 参数,后续任意位置/关键字参数,返回 A 的子类实例
create: t.ClassVar[Callable[t.Concatenate[int, ...], A]] = classmethod(
lambda cls, a, **kw: cls(a)
) # type: ignore[assignment]
class B(A):
def __init__(self, a: int, b: int) -> None:
super().__init__(a)
self.b = b
@classmethod
def create(cls, a: int, b: int, **keywords: t.Any) -> t.Self:
return cls(a, b) # ✅ mypy 通过:子类实现满足基类 Callable 约束
class C(A):
def __init__(self, a: str, b: int) -> None: # 注意:构造器类型已不同
self.a = a
self.b = b
@classmethod
def create(cls, a: str, b: int, **keywords: t.Any) -> t.Self:
return cls(a, b) # ❌ mypy 报错:返回类型 A 不兼容 str 参数 → 提前暴露设计不一致关键要点:
⚠️ 注意事项: 需安装 typing_extensions >= 4.9.0(支持 Concatenate); Self 在 Python该方案在类型安全、可读性与灵活性间取得平衡,是现代 Python 工厂模式类型提示的最佳实践。