栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

约束的TypeVar和Union之间有什么区别?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

约束的TypeVar和Union之间有什么区别?

T
的类型必须在给定范围内的多种用途之间保持一致,而
U
的类型则不一致。

使用

Union
类型作为函数参数时,参数以及返回类型都可以不同:

U = Union[int, str]def union_f(arg1: U, arg2: U) -> U:    return arg1x = union_f(1, "b")  # No error due to different typesx = union_f(1, 2)  # Also no errorx = union_f("a", 2)  # Also no errorx # And it can't tell in any of the cases if 'x' is an int or string

将其与

TypeVar
参数类型必须匹配的类似情况进行比较:

T = TypeVar("T", int, str)def typevar_f(arg1: T, arg2: T) -> T:    return arg1y = typevar_f(1, "b")  # "Expected type 'int' (matched generic type 'T'), got 'str' insteady = typevar_f("a", 2)  # "Expected type 'str' (matched generic type 'T'), got 'int' insteady = typevar_f("a", "b")  # No errory  # It knows that 'y' is a stringy = typevar_f(1, 2)  # No errory  # It knows that 'y' is an int

因此,

TypeVar
如果允许使用多种类型,请使用a ,但
T
单个作用域内的不同用法必须彼此匹配。
Union
如果允许使用多种类型,则使用a
,但是
U
在给定范围内的不同用法不需要相互匹配。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/429133.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号