假设您有一个继承自 Generic[T] 的 Python 类。有没有办法获得从类/实例中传入的实际类型?
例如,
from typing import TypeVar, Type
T = TypeVar('T')
class Test(Generic[T]):
def hello(self):
my_type = T # this is wrong!
print( "I am {0}".format(my_type) )
Test[int]().hello() # should print "I am int"
Run Code Online (Sandbox Code Playgroud)
在这里,建议类型 arg 出现在类型的 args 字段中。而且确实,
print( str( Test[int].__args__ ) )
Run Code Online (Sandbox Code Playgroud)
将打印 (<class 'int'>,)。但是,我似乎无法直接从实例中访问它,例如替换
my_type = self.__class__.__args__ # this is also wrong (None)
Run Code Online (Sandbox Code Playgroud)
似乎没有诀窍。
谢谢