[python3]函数注解

[python3]函数注解

函数注解是完全可选的元数据,用于用户定义函数。
注解被存储于函数的__annotations__属性中,做为一个字典(dict),并且对函数的其它部分没有影响。参数注解由一个冒号(:)后面加参数名,跟一个表达式作为注解内容。返回注解由“->”定义,跟一个表达式,在参数列表和冒号之间为def语句的结尾。

下面举例了位置参数、关键字参数和返回值注解:

>>> def f(ham: str, eggs: str = 'eggs') -> str:
...     print("Annotations:", f.__annotations__)
...     print("Arguments:", ham, eggs)
...     return ham + ' and ' + eggs
...
>>> f('spam')
Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs
'spam and eggs'

发表回复