2024-05-20 21:29:20 发布
网友
我试图检查参数是否是类声明中指定的泛型类型的实例。然而,Python似乎不允许这样做
T = TypeVar('T') class MyTypeChecker(Generic[T]): def is_right_type(self, x: Any): return isinstance(x, T)
这会产生错误'T' is a type variable and only valid in type context
'T' is a type variable and only valid in type context
您可以使用__orig_class__属性,但请记住,这是一个实现细节,在本answer中有更多细节
__orig_class__
from typing import TypeVar, Generic, Any T = TypeVar('T') class MyTypeChecker(Generic[T]): def is_right_type(self, x: Any): return isinstance(x, self.__orig_class__.__args__[0]) # type: ignore a = MyTypeChecker[int]() b = MyTypeChecker[str]() print(a.is_right_type(1)) # True print(b.is_right_type(1)) # False print(a.is_right_type('str')) # False print(b.is_right_type('str')) # True
您可以使用
__orig_class__
属性,但请记住,这是一个实现细节,在本answer中有更多细节相关问题 更多 >
编程相关推荐