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的使用方式

相关推荐
Pyeako几秒前
opencv计算机视觉--DNN模块实现风格迁移
python·opencv·计算机视觉·pycharm·dnn·预处理·风格迁移
m0_70665323几秒前
用Python创建一个Discord聊天机器人
jvm·数据库·python
枫叶丹42 分钟前
【Qt开发】Qt系统(十一)-> Qt 音频
c语言·开发语言·c++·qt·音视频
tlwlmy6 分钟前
python excel图片批量导出
开发语言·python·excel
ValhallaCoder8 分钟前
hot100-矩阵
数据结构·python·算法·矩阵
散峰而望8 分钟前
【基础算法】穷举的艺术:在可能性森林中寻找答案
开发语言·数据结构·c++·算法·随机森林·github·动态规划
那年我七岁10 分钟前
android ndk c++ 绘制图片方式
android·c++·python
Java后端的Ai之路10 分钟前
【Python教程10】-开箱即用
android·开发语言·python
散峰而望11 分钟前
【基础算法】算法的“预谋”:前缀和如何改变游戏规则
开发语言·数据结构·c++·算法·github·动态规划·推荐算法
深蓝电商API15 分钟前
异步爬虫中代理池的并发管理
开发语言·爬虫·python