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
好处:
使用预期的类型来注释参数,然后在函数返回值验证时检验参数的类型或者将其强制转换成预期的类型。
相关文章
- python的random()函数用法_Python随机函数random用法示例
- python中bool函数_bool()函数以及Python中的示例
- python爬虫—–Python访问http的几种方式「建议收藏」
- python函数–isalpha()方法[通俗易懂]
- python在线代码编辑器-5种最佳Python IDE和代码编辑器
- Python实现http请求的方法
- Python 入门与基础《刷题篇》(1)
- 【说站】python定义数值类型变量的方法
- 关于python中lambda函数的描述_Python全局变量
- python如何生成随机数_Python生成50个随机数
- Python安装失败_python第三方库安装失败
- ChatGPT竟写出毁灭人类计划书,还给出相应Python代码,网友:AI正在指数级发展
- Python数据类型怎么转换?数据类型转换函数命令示语句及常见问题
- Python实现图像与Base64格式互转
- Python使用platform库获取系统信息:操作系统信息、硬件信息、python环境信息
- Python tempfile模块:生成临时文件和临时目录
- Python输出函数print()总结(python print())详解编程语言
- Python操作MongoDB数据库(简明版)
- 提升Linux环境:升级Python(linux升级python)
- 在Linux上运行Python脚本的简单指南(linux运行python)
- Python如何连接MySQL数据库(python怎么连接mysql数据库)