python3函数注释 python3新特性函数注释Function Annotations用法分析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python3函数注释 python3新特性函数注释Function Annotations用法分析

feelang   2021-03-22 我要评论
想了解python3新特性函数注释Function Annotations用法分析的相关内容吗,feelang在本文为您仔细讲解python3函数注释的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:python3,函数注释,下面大家一起来学习吧。

本文分析了python3新特性函数注释Function Annotations用法。分享给大家供大家参考,具体如下:

Python 3.X新增加了一个特性(Feature),叫作函数注释 Function Annotations

它的用途虽然不是语法级别的硬性要求,但是顾名思义,它可做为函数额外的注释来用。

Python中普通的函数定义如下:

def func(a, b, c):
  return a + b + c
>>> func(1, 2, 3)
6

添加了函数注释的函数会变成如下形式:

def func(a: 'spam', b: (1, 10), c: float) -> int:
  return a + b + c
>>> func(1, 2, 3)
6

注释的一般规则是参数名后跟一个冒号(:),然后再跟一个expression,这个expression可以是任何形式。

返回值的形式是 -> int,annotation可被保存为函数的attributes。

查看所有的annotation,可通过如下语句:

>>> func.__annotations__
{'c': <class 'float'>, 'a': 'spam', 'b': (1, 10), 'return': <class 'int'>}

如果为函数增加了注释,可不可以继续使用默认参数呢?答案是肯定的。

>>> def func(a: 'spam' = 4, b: (1, 10) = 5, c: float = 6) -> int:
...  return a + b + c
...
>>> func(1, 2, 3)
6
>>> func()
15
>>> func(1, c=10)
16
>>> func.__annotations__
{'c': <class 'float'>, 'a': 'spam', 'b': (1, 10), 'return': <class 'int'>}

希望本文所述对大家Python程序设计有所帮助。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们