首页 > 解决方案 > 可变数量的泛型类型

问题描述

我正在努力解决我想指定继承自的类typing.Generic可以具有多种类型的情况。请看以下简单示例:

from typing import *

T = TypeVar('T')

class C(Generic[T]):
    data: Tuple[int, T]

c = C[str]()
c.data = 4, '4'

这种情况下工作正常,但data只允许成对(两个元组)。我想以C支持任何长度和任何类型的元组的方式编写,其中第一个元素是int- 只要指定了类型。特别是我想要一个允许以下操作的结构(不一定在这种语法中):

c1 = C[str]()
c1.data = 1, '1'   # should work
c1.data = 1, '1', '1'  # should report an error

c2 = C[str, float]()
c2.data = 1, '1', 1.0  # should work
c2.data = 1, '1'  # should report an error
c2.data = 1, '1', '1'  # should report an error

有什么方法可以从 python / mypy 获得描述的行为?

标签: pythonpython-3.xmypypython-typing

解决方案


推荐阅读