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

如何在typing.Generic子类的构造方法中访问类型实参?

如何在Python泛型类的__init__中访问指定的类型参数?

可以在对象构造阶段访问到Foo[int]里的int类型,具体实现分Python版本:

Python 3.10+ 原生支持

从Python 3.10开始,泛型类的实例会自动带有__orig_class__属性,存储了实例化时的完整泛型类型信息,配合typing.get_args就能提取出类型参数:

from typing import TypeVar, Generic, get_args

T = TypeVar("T")
class Foo(Generic[T]):
    def __init__(self):
        # 获取实例化时的原始泛型类
        orig_generic = self.__orig_class__
        # 提取第一个类型参数
        self.target_type = get_args(orig_generic)[0]
        print(f"当前泛型类型参数: {self.target_type}")

# 测试
foo_int = Foo[int]()  # 输出:当前泛型类型参数: <class 'int'>
foo_str = Foo[str]()  # 输出:当前泛型类型参数: <class 'str'>

Python 3.9及以下版本

早期版本没有__orig_class__属性,可采用两种替代方案:

  1. 显式传递类型参数:实例化时手动把类型传入__init__,这是最直接的方式:
from typing import TypeVar, Generic

T = TypeVar("T")
class Foo(Generic[T]):
    def __init__(self, target_type: type):
        self.target_type = target_type
        print(f"当前泛型类型参数: {self.target_type}")

# 测试
foo_int = Foo[int](int)  # 输出:当前泛型类型参数: <class 'int'>
  1. 借助第三方工具:使用typing_inspect库(需自行安装)的get_args和get_origin方法解析泛型类型信息,不过需要额外依赖。

注意点

Python的类型提示默认遵循类型擦除机制(PEP 484),泛型类本身在运行时不会保留类型参数信息,但__orig_class__是Python为泛型实例专门保留的特殊属性,用于在运行时获取实例化时的泛型类型细节。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:35:02