简体   繁体   English

如何在 Python 中的泛型类型上使用 isinstance

[英]How to use isinstance on a generic type in Python

I'm trying to check whether an argument is an instance of the generic type specified in the class declaration.我正在尝试检查参数是否是 class 声明中指定的泛型类型的实例。 However Python does not seem to allow this.然而 Python 似乎不允许这样做。

T = TypeVar('T')
class MyTypeChecker(Generic[T]):
    def is_right_type(self, x: Any):
        return isinstance(x, T)

This gives the error 'T' is a type variable and only valid in type context .这给出了错误'T' is a type variable and only valid in type context

You could use the __orig_class__ attribute, but keep in mind that this is an implementation detail, in more detail in this 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM