【问题标题】:custom metatype for type hinting用于类型提示的自定义元类型
【发布时间】:2017-06-18 22:21:05
【问题描述】:

我正在尝试定义一个自定义元类型以用于类型提示。例如

print(Tuple[int, str, bool])
print(CustomType[int, str, bool])

显然,第一行工作正常。我将如何实现CustomType,以便它也可以工作?我试过这个:

class CustomType(Tuple):
    pass

并得到错误TypeError: __main__.CustomType is not a generic class。 我的目标是通过额外的类方法对 Tuple 进行专业化

【问题讨论】:

    标签: python python-3.x generics type-hinting


    【解决方案1】:

    AFAIK 你可以做到这一点,但以一种受限制的形式,我认为你不能指定可变数量的参数,而是指定确切的参数数量。

    当您将 Tuple 作为基类提供时,您需要向它提供一些类型变量:

    from typing import Tuple, TypeVar
    T1, T2, T3 = TypeVar('T1'), TypeVar('T2'), TypeVar('T3')
    
    class CustomType(Tuple[T1, T2, T3]): 
        pass
    
    print(CustomType[int, str, bool])
    # __main__.CustomType[int, str, bool]
    

    现在可以附加3 类型,您需要使用CustomType(Tuple[T1, T2])2 类型创建自定义类型,依此类推。

    顺便说一句,Issue 299 中添加了对子类化 Tuple(和 Callable)的支持,并且可用于 3.6+

    【讨论】:

      猜你喜欢
      • 2020-11-23
      • 2021-10-09
      • 2016-02-23
      • 2019-08-14
      • 2021-11-16
      • 2015-05-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      相关资源
      最近更新 更多