相关疑难解决方法(0)

Generic[T] 基类 - 如何从实例中获取 T 的类型?

假设您有一个继承自 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)

似乎没有诀窍。

谢谢

python generics python-3.x

10
推荐指数
4
解决办法
1874
查看次数

标签 统计

generics ×1

python ×1

python-3.x ×1