python列表注解

示例代码

from typing import List


def test_basic() -> List[int or float]:
    return [1, 2, 3, 4]


if __name__ == '__main__':
    my_list: List[int or float] = test_basic()

更多注解

Type Description
int 整型
float 浮点数字
bool 布尔
str 字符串
bytes 8位字符
object 任意对象
List(str) 字符串组成的列表
Tuple[int, …] 任意数量的int对象的元组
Tuple[int, int] 两个int对象的元组
Dict[str, int] 键是 str 值是 int 的字典
Iterable[int] 包含 int 的可迭代对象
Sequence[bool] 布尔值序列(只读)
Mapping[str, int] 从 str 键到 int 值的映射(只读)
Any 具有任意类型的动态类型值
Union 联合类型
Optional 参数可以为空或已经声明的类型
Mapping 映射,是 collections.abc.Mapping 的泛型
MutableMapping Mapping 对象的子类,可变
Generator 生成器类型, Generator[YieldType、SendType、ReturnType]
NoReturn 函数没有返回结果
Set 集合 set 的泛型, 推荐用于注解返回类型
AbstractSet collections.abc.Set 的泛型,推荐用于注解参数
Sequence ollections.abc.Sequence 的泛型,list、tuple 等的泛化类型
TypeVar 自定义兼容特定类型的变量
NewType 声明一些具有特殊含义的类型
Callable 可调用类型, Callable[[参数类型], 返回类型]

猜你喜欢

转载自blog.csdn.net/weixin_35757704/article/details/121752712