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
相关产品推荐
相关产品推荐

