如何在运行时检查 TypeVar 的类型
How to check TypeVar's Type at runtime
我有一个通用的 class Graph[Generic[T], object]
.
我的问题是,是否有任何 returns 类型的函数作为泛型传递给 class Graph
>>> g = Graph[int]()
>>> magic_func(g)
<class 'int'>
这是实现此目的的一种方法,适用于 Python 3.6+(在 3.6、3.7 和 3.8 中测试过):
from typing import TypeVar, Generic
T = TypeVar('T')
class Graph(Generic[T], object):
def get_generic_type(self):
print(self.__orig_class__.__args__[0])
if __name__=='__main__':
g_int = Graph[int]()
g_str = Graph[str]()
g_int.get_generic_type()
g_str.get_generic_type()
输出:
<class 'int'>
<class 'str'>
如果您想获取 __new__
或 __init__
中的类型,事情会变得有点棘手,请参阅以下 post 了解更多信息:
编辑
库 pytypes 似乎提供了一种允许从 init 获取 orig_class 的方法,请检查此处可用的方法 get_orig_class
:https://github.com/Stewori/pytypes/blob/master/pytypes/type_util.py
我有一个通用的 class Graph[Generic[T], object]
.
我的问题是,是否有任何 returns 类型的函数作为泛型传递给 class Graph
>>> g = Graph[int]()
>>> magic_func(g)
<class 'int'>
这是实现此目的的一种方法,适用于 Python 3.6+(在 3.6、3.7 和 3.8 中测试过):
from typing import TypeVar, Generic
T = TypeVar('T')
class Graph(Generic[T], object):
def get_generic_type(self):
print(self.__orig_class__.__args__[0])
if __name__=='__main__':
g_int = Graph[int]()
g_str = Graph[str]()
g_int.get_generic_type()
g_str.get_generic_type()
输出:
<class 'int'>
<class 'str'>
如果您想获取 __new__
或 __init__
中的类型,事情会变得有点棘手,请参阅以下 post 了解更多信息:
编辑
库 pytypes 似乎提供了一种允许从 init 获取 orig_class 的方法,请检查此处可用的方法 get_orig_class
:https://github.com/Stewori/pytypes/blob/master/pytypes/type_util.py