zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python中def函数右侧有个->的含义

Python 函数 含义 右侧 有个
2023-09-14 09:15:41 时间

“->”为函数标注,通常用于类型提示,是python3中引入的用法。

这是一个叫做返回值注解的符号。它通过允许将元数据附加到描述其参数和返回值的函数来扩展该功能。

例如:

在有->的情况下:

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

而无->的情况下:

def f(ham: str, eggs: str = 'eggs'):
    print("Annotations:", f.__annotations__)
    print("Arguments:", ham, eggs)
    return ham + ' and ' + eggs
 
f('spam')

运行结果是:

Annotations: {'ham': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs

好处:

使用预期的类型来注释参数,然后在函数返回值验证时检验参数的类型或者将其强制转换成预期的类型。