我试图检查参数是否是类声明中指定的泛型类型的实例。然而Python似乎不允许这样做。
T = TypeVar('T')
class MyTypeChecker(Generic[T]):
def is_right_type(self, x: Any):
return isinstance(x, T)
Run Code Online (Sandbox Code Playgroud)
这给出了错误'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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9781 次 |
| 最近记录: |