美文网首页python学习
python:给函数增加元信息

python:给函数增加元信息

作者: 跳蚤窝 | 来源:发表于2019-08-09 10:26 被阅读0次

参数注解

一般来说python语言没有类型声明,有些时候我们很难读懂参数到底是什么类型,这个时候我们就需要一个类似与C一样的函数命名方式,来显示的注解函数参数了。

def add(x:int=..., y:int=...) -> int:
     return  x + y

这样就完成了对函数的注解,一般来说

  • 我们可以使用任意类型的对象给函数添加注解
  • python解释器并不会理会任何注解
add(5, 6) # return 11
add(5.5, 6) # return 11.5

上面两种使用方法并不会报错(python3.7之前)。

获取注解

第三方工具

help(add)

输出结果为:

help on function add in module __main__:
add(x:int, y:int) ->int

annotations

print(add.__annotations__)

输出为:

{'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}

相关文章

网友评论

    本文标题:python:给函数增加元信息

    本文链接:https://www.haomeiwen.com/subject/hzzlrctx.html