【问题标题】:Python 3 types, custom variadic generic type with arbitrary number of contained types, how?Python 3 类型,具有任意数量的包含类型的自定义可变参数泛型,如何?
【发布时间】:2018-03-11 06:51:21
【问题描述】:

typing.Tuple 类可以与任意数量的类型参数一起使用,例如 Tuple[int, str, MyClass]Tuple[str, float]。我如何实现我自己的可以这样使用的类?我了解如何从typing.Generic 继承。下面的代码演示了这一点。

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)

上面的代码可以工作,但类型检查器(在我的例子中是 PyCharm)会发现t 的类型应该是Thing[int] 而不是Thing[str]。这一切都很好,但是我如何让Thing 类支持任意数量的类型参数,就像Tuple 一样?

【问题讨论】:

标签: python-3.x types typing variadic


【解决方案1】:
  • 在您的示例中,t 的类型为 Thing,而不是 Thing[str]。所以这个对象接受T 的任何东西。
  • 您可以像这样对其进行参数化:t2 = Thing[str]("WTF")
  • 现在,对于你的问题,我想你想像这样使用typing.Uniont3=Thing[Union[str,int,float]]("WTF")

顺便说一句,你可以使用typing_inspect中的get_generic_type()来检查泛型的类型

>>> get_generic_type(t)
__main__.Thing
>>> get_generic_type(t2)
__main__.Thing[str]
>>> get_generic_type(t3)
__main__.Thing[typing.Union[str, int, float]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多