Python Function Annotations - Python 函数标注

Python Function Annotations - Python 函数标注

More Control Flow Tools


1. Function Annotations - 函数标注

Function annotations are completely optional metadata information about the types used by user-defined functions (see PEP 3107 and PEP 484 for more information).
函数标注是关于用户自定义函数中使用的类型的完全可选元数据信息 (有关详情请参阅 PEP 3107 和 PEP 484)。

Annotations are stored in the __annotations__ attribute of the function as a dictionary and have no effect on any other part of the function. Parameter annotations are defined by a colon after the parameter name, followed by an expression evaluating to the value of the annotation. Return annotations are defined by a literal ->, followed by an expression, between the parameter list and the colon denoting the end of the def statement. The following example has a positional argument, a keyword argument, and the return value annotated:
函数标注以字典的形式存放在函数的 __annotations__ 属性中,并且不会影响函数的任何其他部分。形参标注的定义方式是在形参名称后加上冒号,后面跟一个表达式,该表达式会被求值为标注的值。返回值标注的定义方式是加上一个组合符号 ->,后面跟一个表达式,该标注位于形参列表和表示 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'
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页