You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何为process方法标注返回_process方法的类型?

解决方案

你遇到的问题是因为TypeVar未与泛型类绑定,导致mypy无法识别其关联关系。正确的做法是将TypeVar定义在类外部,并让Thing类继承Generic[T],以此建立方法返回类型的关联。

正确的类型标注代码

from abc import abstractmethod
from typing import TypeVar, Generic

# 在类外部定义TypeVar
T = TypeVar("T")

class Thing(Generic[T]):
    @abstractmethod
    def _process(self) -> T:
        ...

    def pre_process(self, x: int) -> None:
        # 补充pre_process的类型提示,原代码中存在该调用
        ...

    def process(self, x: int) -> T:
        self.pre_process(x)
        return self._process()

说明

  • 将TypeVar移到类外部,并让Thing继承Generic[T],使类成为泛型类,mypy就能正确关联_process和process的返回类型。
  • 补充pre_process的类型提示,避免mypy对未标注方法的警告。
  • 子类实现时可指定具体返回类型,示例如下:
class NumberThing(Thing[int]):
    def _process(self) -> int:
        return 100

    def pre_process(self, x: int) -> None:
        print(f"预处理{x}")

# mypy会自动推断result的类型为int
result = NumberThing().process(5)

内容的提问来源于stack exchange,提问作者2e0byo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 12:34:56