python3 -> 函数注释 Function Annotations

来源:互联网 发布:小米秒杀软件 编辑:程序博客网 时间:2024/05/17 23:16

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'>}


参考文献

Learning Python 5th Edition


0 0
原创粉丝点击