Python3类型注解

函数注解

定义函数的时候对参数和返回值添加注解.

1
2
def add(a: int, b: int, c: str = 5) -> tuple:
return a,b,c
  • a: int 注解参数
  • c: str = 5 注解有默认值的参数
  • -> tuple 注解返回值类型

注解内容既可以是类型说明,也可以是字符串,也可以是表达式

1
2
def add(a: 1+1) -> 1 + 1:
return a

获取定义函数的注解

  • 使用__annotations__,例如add.__annotations.

  • inspect.signature:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import inspect
    sig = inspect.signature(add)
    # 字典类型
    print(sig.paraments)

    # 参数注解
    for k, v in sig.parameters.items():
    print('{k}: {a!r}'.format(k=k, a=v.annotation))

    # 返回值注解
    print(sig.return_annotation)
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2017-2021 More Star

请我喝杯咖啡吧~

支付宝
微信