繁体   English   中英

类型提示的自定义元类型

[英]custom metatype for type hinting

我正在尝试定义用于typehinting的自定义元类型。 例如

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

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

class CustomType(Tuple):
    pass

并获取错误TypeError: __main__.CustomType is not a generic class 我的目标是使用额外的类方法对Tuple进行专门化

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

当您将它作为基类提供时,您需要为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种类型,您需要为2种类型创建CustomType(Tuple[T1, T2])自定义类型,依此类推。

顺便说一句,对于子类支持Tuple (和Callable的加入) 发行299 ,可供3.6+

暂无
暂无

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

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