如何在 Python 中对泛型类型使用 isinstance
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
我正在尝试检查参数是否是 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