python-3.x - 函数返回多种类型时如何指定变量的返回类型

标签 python-3.x python-typing

在Python中,一个函数可以返回多种类型,例如,在下面的示例中,astrbint cList[int]

def test():
    return 'abc', 100, [0, 1, 2]

a, b, c = test()

print(a)
# abc

print(b)
# 100

print(c)
# [0, 1, 2]

所以函数签名就变成了,

def test() -> Tuple[str, int, List[int]]:

在这种情况下,如何指定接收值的变量类型?

假设我应该能够指定它,如下所示,但这是不可能的。

 a: str, b: int, c: List[int] = test()

唯一可行的替代方案如下所示,

ret: Tuple(str, int, List[int]) = test()

但是随后我需要将元组解包为多个变量,然后我们又回到了第一个方,因为我们无法指定这些变量的类型。

我错过了什么?

最佳答案

使用类型提示怎么样?

(
    a,  # type: str
    b,  # type: int
    c,  # type: List[int]
) = test()

无论如何,即使没有在最终变量中明确指定类型,类型也应该足够智能以推断出正确的类型。

关于python-3.x - 函数返回多种类型时如何指定变量的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74667417/

相关文章:

python - 包内显式相对导入不使用关键字 from

python - 键入一个带有可调用的函数

Python 为列表的子类打字

python - 如何编写一个满足typing.TextIO 的类文件?

python - 来自 plt.subplots() 的 matplotlib 轴的精确类型注释数组 (numpy.ndarray)

mysql - 如何从 select 语句向表中插入信息?

Python 请求 api 不在表体中获取数据

python - 如何在没有 eval 的情况下取消列表/元组的字符串

python - Python 类型提示语法如何/为什么起作用?

performance - 哪个 pyzmq 实现在 @gen.coroutine、@asyncio.coroutine 和 async 之间具有最快的吞吐量?