
如何获取 uniontype 的子成员
利用 uniontype 可表示多个类型的联合体,但在某些情况下,我们可能需要获取并判断其子类型。本文将介绍如何解决此问题。
判断类型是否在 uniontype 中
可以使用 typing.get_args 来获取 uniontype 的子成员,具体代码如下:
from typing import union type_hint = union[str, int] get_args(type_hint) # [str, int]
这样就可以获取到 uniontype 的子成员列表。
判断字符串是否在 uniontype 中
为了判断一个字符串是否在 uniontype 中,可以使用 isinstance 函数:
from typing import Union
type_hint = Union[str, int]
isinstance("", type_hint) # True
isinstance(10, type_hint) # False以上就是如何获取 UnionType 的子成员并判断类型是否在其中?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号