[英]How to use isinstance on a generic type in Python
我正在尝试检查参数是否是 class 声明中指定的泛型类型的实例。 然而 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
。
您可以使用__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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.