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

如何通过Python泛型类A的类型对象访问Generic[T]泛型基类?

访问泛型类的带参数基类Generic[T]

针对你定义的泛型类:

from typing import TypeVar, Generic

T = TypeVar("T")

class A(Generic[T]):
    a: T

要获取Generic[T]这个带类型参数的基类,不能直接用__bases__——因为__bases__返回的是未绑定类型参数的原始基类Generic。你可以通过以下两种方式实现:

方法1:使用__orig_bases__属性(CPython实现细节)

CPython解释器会给泛型类添加__orig_bases__属性,它存储了类定义时的原始基类(包含类型参数):

print(A.__orig_bases__)
# 输出:(typing.Generic[~T],)

这个属性是CPython的特定实现,其他Python解释器(如PyPy)可能不支持,但在绝大多数日常场景中可以正常使用。

方法2:结合get_origin和get_args构造

如果想避免依赖解释器实现细节,可以手动构造带参数的Generic[T]:

from typing import get_origin, get_args

# 从泛型类实例中提取参数并构造目标基类
generic_with_args = get_origin(Generic[T])[get_args(A[T])]
print(generic_with_args)
# 输出:typing.Generic[~T]

或者直接从__orig_bases__中筛选:

generic_with_args = next(base for base in A.__orig_bases__ if get_origin(base) is Generic)
print(generic_with_args)
# 输出:typing.Generic[~T]

原方法失效的原因

get_origin(A[...])返回的是原始类A,它的__bases__存储的是类继承时的非泛型基类(即Generic而非Generic[T])。泛型参数是在类实例化(如A[int])时才绑定的,类本身A的基类并未携带参数信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 00:45:59