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

如何为返回泛型类属性的Python函数指定类型提示?

Python泛型类属性获取函数的类型提示实现

你需要复用已定义的TypeVar来关联函数的输入参数类型和返回值类型,修改后的var_getter函数如下:

import typing as typ

T = typ.TypeVar("T")

class Foo(typ.Generic[T]):
    """The generic class."""
    def __init__(self, var: T):
        self.var = var

def var_getter(foo_obj: Foo[T]) -> T:
    """Var getter."""
    return foo_obj.var

关键说明:

  • 利用已声明的T = typ.TypeVar("T"),让函数的输入与输出类型形成绑定关系。
  • 参数foo_obj的类型指定为Foo[T],表示它是泛型类Foo的实例,其泛型参数为T。
  • 返回类型指定为T,意味着函数返回的foo_obj.var类型会和Foo实例的泛型参数类型保持一致。

测试用例验证:

注意你提供的测试代码中test_2存在笔误,应传入Baz(1)而非Bar(1),修正后:

class Bar(Foo[str]):
    pass

test_1 = var_getter(Bar("a")) # 类型检查器会推断test_1为str类型

class Baz(Foo[int]):
    pass

test_2 = var_getter(Baz(1)) # 类型检查器会推断test_2为int类型

此时类型检查器会正确识别test_1和test_2的类型,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:50:23