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

如何为依赖子类的Python函数标注返回类型?

解决方案

要实现IDE根据传入的子类自动推断fn_caller的返回类型,你需要结合TypeVar、Type和ReturnType来完成类型标注,具体实现如下:

完整代码示例

from typing import TypeVar, Type, ReturnType

# 定义泛型变量T,绑定到Base类及其子类
T = TypeVar('T', bound='Base')

class Base:
    @classmethod
    def fn(cls) -> None:
        return None

class A(Base):
    @classmethod
    def fn(cls) -> int:
        return 0

class B(Base):
    @classmethod
    def fn(cls) -> str:
        return "str"

def fn_caller(c: Type[T]) -> ReturnType[T.fn]:
    return c.fn()

a = fn_caller(A)  # IDE会自动推断a的类型为int
b = fn_caller(B)  # IDE会自动推断b的类型为str

核心逻辑说明

  • Type[T]用于标注参数c是T类本身(而非类的实例),同时T被约束为Base的子类,确保传入的类必然包含fn类方法。
  • ReturnType[T.fn]会动态提取T类中fn方法的返回类型,让类型检查器能够根据传入的具体子类,自动推导fn_caller的返回类型。

如果你的Python版本在3.10及以上,还可以省略ReturnType的导入,直接使用T.fn.__return_type__达到同样效果:

def fn_caller(c: Type[T]) -> T.fn.__return_type__:
    return c.fn()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 08:27:34