参考博文:https://blog.csdn.net/Leon_winter/article/details/87931440

python3提供了一种为函数提供注释的方法,可以对函数参数、返回值进行注释

例子如下:

复制代码

def test(x:int, y: 'int > 0', z:'中文', k:'int > 0' = 1) -> 'str':
    pass

print(text.__annotations__)
# __annotations__前后均是两个下划线
# 输出为字典形式,'return'是对返回值的注释,输出如下:
# {'x': int, 'y': 'int > 0', 'z': '中文', 'k': 'int > 0', 'return': 'str'}

复制代码

参数注释:

        普通形参:x:int, y: 'int > 0', z:'中文'

        默认形参注释:k:'int > 0' = 1

返回值注释:def test( ) -> 'str':

注释存入了 __annotations__ 属性中,使用 函数点属性,打印注释,返回字典

 

注意:

如果函数参数既要设定初始值(默认形参),又要进行注释,注释应该放在":“号与”=“号之间;如果要注释返回值,注释放在”)“与”:“之间,并加上”->"。

  Python3对注释所做的唯一的事情是,把他们存储在函数的__annotations__属性里。仅此而已,Python3不做检查,不做强制,不做验证,什么操作都不做。换句话,注解对Python解释器没任何意义。注解只是元数据,可以供IDE、框架和装饰器等工具使用。

 

 posted on 2019-12-03 11:14  墨语i  阅读(2705)  评论(0)    收藏  举报