如何访问泛型类的参数



如果我有一个类a:

T = TypeVar("T")
class A(Generic[T]):
a: T

如何使用类型对象A访问Generic[T]

typing.get_origin(A[...]).__bases__只是返回<class 'typing.Generic'>而不是typing.Generic[~T]

您正在寻找__orig_bases__。这是在创建新类时由type元类设置的。PEP 560中提到了这一点,但在其他方面几乎没有记录。

该属性包含(顾名思义(原始基,因为它们以元组的形式传递给元类构造函数。这将它与__bases__区分开来,后者包含types.resolve_bases返回的已解析的碱基。

下面是一个工作示例:

from typing import Generic, TypeVar
T = TypeVar("T")
class A(Generic[T]):
a: T
class B(A[int]):
pass
print(A.__orig_bases__)  # (typing.Generic[~T],)
print(B.__orig_bases__)  # (__main__.A[int],)

由于它的记录很差,我会小心你在哪里使用它。如果你在你的问题中添加更多的上下文,也许我们会找到更好的方法来完成你想要的。

可能相关或感兴趣:

用户定义的Generic[T]类的任何特定子类中的访问类型参数

最新更新