码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-06-06 00:11:42      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:用途   特性   attribute   nbsp   答案   它的   UNC   形式   规则   

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

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

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

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

def func(a,b):
    return a+b

print(func(1, 2))
#3

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

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

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

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

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

def func(a: haha, b: (1, 10), c: float) -> int:
  return a + b + c
print(func(1, 2, 3))
print(func.__annotations__)
#6
#{‘a‘: ‘haha‘, ‘b‘: (1, 10), ‘c‘: <class ‘float‘>, ‘return‘: <class ‘int‘>}

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

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

 

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

标签:用途   特性   attribute   nbsp   答案   它的   UNC   形式   规则   

原文地址:https://www.cnblogs.com/z-x-y/p/10982325.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!