python - 可变数量的泛型类型
问题描述
我正在努力解决我想指定继承自的类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 获得描述的行为?
解决方案
推荐阅读
- nuget - 如何使用 JFrog CLI 按版本号对 Artifactory 包搜索结果进行排序?
- sql - 如何更改此动态查询
- php - tcpdf 中的 SVG 渲染器不支持 00FF 以上的 UTF-8 字符吗?
- javascript - 将多个动作传递给 bindActionCreators
- r - override.aes 与列表参数的命名向量
- css - 如何应用 CSS 覆盖来阻止相对日期
- node.js - 如何发送使用 mqtt-packet 库生成的 MQTT 数据包?
- spock - 如何在 URL 中使用带有部分路径的 HttpBuilder?
- node.js - 如何使用node.js每5分钟左右使用不同的渲染参数自动更新带有路由“/”的索引页面?
- selenium - 如何在 Cucumber Capybara 测试期间切换到不同的浏览器?