def ->
2020-02-09 本文已影响0人
Poisson_Lee
转载https://www.cnblogs.com/lewic/p/10443573.html
功能注释
函数注释是关于用户定义函数使用的类型的完全可选元数据信息(请参阅PEP 3107和 PEP 484了解更多信息)。
注释__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'>, 'eggs': <class 'str'>, 'return': <class 'str'>}
# Arguments: spam eggs
函数标注通常用于 类型提示:例如以下函数预期接受两个 int 参数并预期返回一个 int 值:
def sum_two_numbers(a: int, b: int) -> int:
return a + b