如何在静态方法中访问Generic类的TypeVar类型变量?
泛型类静态方法中访问TypeVar取值的解决方案
直接用@staticmethod没法实现需求,因为静态方法属于原始泛型类(Foo),不是具体化后的泛型类(Foo[int]),拿不到绑定的类型参数。得改用@classmethod,通过cls参数获取具体化后的类对象,再提取类型参数。
实现代码
from typing import TypeVar, Generic, get_args T = TypeVar("T") class Foo(Generic[T]): @classmethod def print(cls): # 从具体化类中提取泛型参数 type_param = get_args(cls.__orig_class__)[0] print(type_param) Foo[int].print() # 输出: <class 'int'>
关键说明
- 替换
@staticmethod为@classmethod:调用Foo[int].print()时,cls参数会传入具体化后的Foo[int]类对象。 - 使用
get_args(cls.__orig_class__):__orig_class__指向原始泛型类Foo,get_args能提取出它绑定的类型参数int。
如果想要更简洁的输出(比如只打印int而非<class 'int'>),可以把打印语句改成print(type_param.__name__),输出结果就是int。
内容的提问来源于stack exchange,提问作者JRR
相关产品推荐
相关产品推荐

