Python - Union联合类型注解

类型注解

Union类型注解

1.理解union类型

2.掌握使用union进行联合类型注解

Uion类型

python 复制代码
from typing import union
my_list: list[Union[str,int]] = [1,2,"itheima","itcast"]
my_dict: dict[str,Union[str,int]] = {"name":"周杰伦","age":13}

# 使用Union[类型,......,类型]
# 可以定义联合类型注解

Union联合类型注解,在变量注解、函数(方法)形参和返回值注解中,均可使用

python 复制代码
my_list: list[Union(int,str)] = [1,2,"itcast","itheima"]
my_dict: dict[str,Union[str, int]] = {"name":"周杰伦","age": 31}

def func(data: Union[int, str]) -> Union[int, str]:
	pass
python 复制代码
"""
	Union联合类型注解
""
# 使用Union类型,必须先导包
from typing import Union

my_list: list[Union[int,str]] = [1,2,"itheima","itcast"]

def func(data: Union[int,str]) -> Union(int, str):
	pass

func()

总结

1.什么是Union类型

使用Union可以定义联合类型注解

2.Unionz的使用方式

相关推荐
曲幽6 小时前
别再用网页翻译看源码了!你的私人翻译神器LibreTranslate,部署避坑指南来了
python·docker·web·pot·translate·libretranslate·arogstranslate
用户556918817538 小时前
#从脚本到独立程序:Python + Playwright 批量抓取的完整踩坑记录
python·自动化运维
兵慌码乱1 天前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2
luckdewei1 天前
FastAPI 资产管理系统实战:复杂 ORM 关联、Alembic 迁移与 N+1 查询优化
python
aqi001 天前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn1 天前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵2 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup112 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill