在Python 3.10及以上版本中,引入了UnionType,它允许你在类型注解中使用|操作符来表示联合类型。例如,int | str表示一个类型可以是int或str。
要判断一个UnionType是否包含特定类型,可以使用isinstance()函数结合typing模块中的get_args()函数。get_args()函数可以获取联合类型中的所有类型参数。
以下是一个示例代码,展示如何判断一个UnionType是否包含特定类型:
from typing import Union, get_args
# 定义一个联合类型
MyUnionType = Union[int, str, float]
# 获取联合类型中的所有类型参数
types_in_union = get_args(MyUnionType)
# 要检查的类型
target_type = str
# 判断目标类型是否在联合类型中
if target_type in types_in_union:
print(f"{target_type} is in the union type.")
else:
print(f"{target_type} is not in the union type.")
Union[int, str, float]:定义了一个联合类型,表示可以是int、str或float。get_args(MyUnionType):获取联合类型中的所有类型参数,返回一个包含所有类型的元组。target_type in types_in_union:检查目标类型是否在联合类型的类型参数中。如果target_type是str,输出将是:
str is in the union type.
如果target_type是list,输出将是:
list is not in the union type.
get_args()函数在Python 3.8及以上版本中可用。|操作符来定义联合类型,而不需要使用Union。希望这个解释对你有帮助!