函数注释示例:
def f(ham: 42, eggs: int = 'spam') -> "Nothing to see here":
print("函数注释", f.__annotations__)
print("参数值打印", ham, eggs)
print(type(ham),type(eggs))
f("www")
返回信息:
函数注释 {'ham': 42, 'eggs': <class 'int'>, 'return': 'Nothing to see here'}
参数值打印 www spam
<class 'str'> <class 'str'>
解释说明:
注释的一般规则是参数名后跟一个冒号(:),然后再跟一个expression,这个expression可以是任何形式。
返回值的形式是 -> int,annotation可被保存为函数的attributes。
以上属于静态注释,还有一种方法叫做动态注释
动态注释的原理,就是在函数中或者装饰器中动态的增加 删除 更改 注释内容
f.__annotations__ 是一个字典,可以使用字典的所有操作,这样就可以动态的更改注释了
大多数情况,我使用的是一下方法,进行注释说明
def foo():
""" This is function foo"""
Google风格
"""
This is a groups style docs.
Parameters:
param1 - this is the first param
param2 - this is a second param
Returns:
This is a description of what is returned
Raises:
KeyError - raises an exception
"""
Rest风格
"""
This is a reST style.
:param param1: this is a first param
:param param2: this is a second param
:returns: this is a description of what is returned
:raises keyError: raises an exception
"""