【发布时间】:2020-06-20 09:19:47
【问题描述】:
我有一个通用类Graph[Generic[T], object]。
我的问题,是否有任何函数返回作为泛型传递给类Graph
>>> g = Graph[int]()
>>> magic_func(g)
<class 'int'>
【问题讨论】:
标签: python generics static-typing
我有一个通用类Graph[Generic[T], object]。
我的问题,是否有任何函数返回作为泛型传递给类Graph
>>> g = Graph[int]()
>>> magic_func(g)
<class 'int'>
【问题讨论】:
标签: python generics static-typing
这是一种在 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__ 中获取类型,事情会有些棘手,请参阅以下帖子了解更多信息:Generic[T] base class - how to get type of T from within instance?
编辑
pytypes 库似乎提供了一种允许从 init 获取 orig_class 的方法,请在此处查看方法 get_orig_class:https://github.com/Stewori/pytypes/blob/master/pytypes/type_util.py
【讨论】: