Python 3 类型,具有任意数量包含类型的自定义可变参数泛型类型,如何? [英] Python 3 types, custom variadic generic type with arbitrary number of contained types, how?
问题描述
typing.Tuple
类可以与任意数量的类型参数一起使用,例如 Tuple[int, str, MyClass]
或 Tuple[str,浮动]
.我如何实现我自己的可以这样使用的类?我了解如何从 typing.Generic
继承.以下代码演示了这一点.
from 打字 import TypeVar, GenericT = TypeVar("T")类事物(通用 [T]):def __init__(self, value: T):self.value = 价值def f(thing: Thing[int]):打印(东西.价值)如果 __name__ == '__main__':t = 东西(WTF")f(t)
上面的代码可以工作,但类型检查器(在我的例子中是 PyCharm)会发现 t
应该是 Thing[int]
类型而不是 东西[str]
.一切都很好,但是如何让 Thing
类支持任意数量的类型参数,就像 Tuple
那样?
- 在您的示例中,
t
的类型为Thing
,而不是Thing[str]
.所以这个对象接受T
的任何东西. - 您可以像这样对其进行参数化:
t2 = Thing[str]("WTF")
- 现在,对于您的问题,我认为您想使用 typing.Union 像这样:
t3=Thing[Union[str,int,float]]("WTF")
顺便说一下,您可以使用 typing_inspect
<预><代码>>>>get_generic_type(t)__主要的事>>>get_generic_type(t2)__main__.Thing[str]>>>get_generic_type(t3)__main__.Thing[typing.Union[str, int, float]]The class typing.Tuple
can be used as with arbitrary number of type arguments, like Tuple[int, str, MyClass]
or Tuple[str, float]
. How do I implement my own class that can be used like that? I understand how to inherit from typing.Generic
. The following code demonstrates this.
from typing import TypeVar, Generic
T = TypeVar("T")
class Thing(Generic[T]):
def __init__(self, value: T):
self.value = value
def f(thing: Thing[int]):
print(thing.value)
if __name__ == '__main__':
t = Thing("WTF")
f(t)
The above code would work but the type checker (in my case PyCharm) would catch the fact that t
should be of type Thing[int]
and not Thing[str]
. That's all fine, but how do I make the class Thing
support arbitrary number of type arguments, like Tuple
does?
- In your example,
t
is of typeThing
, notThing[str]
. So this object accepts anything forT
. - You can parametrize it like this :
t2 = Thing[str]("WTF")
- now, for your question, I think you want to use typing.Union like this:
t3=Thing[Union[str,int,float]]("WTF")
By the way, you can check the type of generics by using get_generic_type() from typing_inspect
>>> get_generic_type(t)
__main__.Thing
>>> get_generic_type(t2)
__main__.Thing[str]
>>> get_generic_type(t3)
__main__.Thing[typing.Union[str, int, float]]
这篇关于Python 3 类型,具有任意数量包含类型的自定义可变参数泛型类型,如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!