Python TypeHint 多个参数hint,多个返回值hint

python >= 3.5 才支持hint

最基本的形式

def foo(a: int, b: float) -> float:
    return a + b
print(foo(1, 2))

如果是参数可能是多种形式,输出也是多个返回值

from typing import Union, Tuple
def foo(a: Union[int, float], b: Union[int, float]) -> Tuple[Union[int, float], float]:
    return a + b, float(a)
print(foo(1, 2))

列表中为某种类型的变量

from typing import Union, Tuple, List
def foo(a: List[Union[str, int]]) -> str:
    sum = ""
    for i in a:
        if isinstance(i, int):
            sum += str(i)
        else:
            sum += i
    return sum
print(foo([1, "+", 1, "=", 2]))

迭代器形式

from typing import Iterator
def fib(n: int) -> Iterator[int]:
  a, b = 0, 1
  while a < n:
    yield a
    a, b = b, a + b

参考:
https://www.jianshu.com/p/0227232239b5
https://blog.csdn.net/chuchus/article/details/77891128
https://stackoverflow.com/questions/33945261/how-to-specify-multiple-return-types-using-type-hints/33945518
https://stackoverflow.com/questions/40181344/how-to-annotate-types-of-multiple-return-values

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值