前言
typing 是在 python 3.5 才有的模块
前置学习
Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html
常用类型提示
https://www.geek-share.com/detail/2840288720.html
类型别名
可以将复杂一点类型给个别名,这样好用一些
变量栗子
# 别名vector = List[float]var: vector = [1.1, 2.2]# 等价写法var: List[float] = [1.1, 2.2]
函数栗子
# float 组成的列表别名vector_list_es = List[float]# 字典别名vector_dict = Dict[str, vector_list_es]# 字典组成列表别名vector_list = List[vector_dict]# vector_list 等价写法,不用别名的话,有点像套娃vector = List[Dict[str, List[float]]]# 函数def scale(scalar: float, vector: vector_list) -> vector_list:for item in vector:for key, value in item.items():item[key] = [scalar * num for num in value]print(vector)return vectorscale(2.2, [{\"a\": [1, 2, 3]}, {\"b\": [4, 5, 6]}])# 输出结果[{\'a\': [2.2, 4.4, 6.6000000000000005]}, {\'b\': [8.8, 11.0, 13.200000000000001]}]
更接近实际应用的栗子
# 更接近实际应用的栗子ConnectionOptions = Dict[str, str]Address = Tuple[str, int]Server = Tuple[Address, ConnectionOptions]def broadcast_message(message: str, servers: Server) -> None:print(message, servers)message = \"发送服务器消息\"servers = ((\"127.0.0.1\", 127), {\"name\": \"服务器1\"})broadcast_message(message, servers)# 输出结果发送服务器消息 ((\'127.0.0.1\', 127), {\'name\': \'服务器1\'})
NewType
https://www.cnblogs.com/poloyy/p/15153886.html
Callable
https://www.geek-share.com/detail/2840288660.html
TypeVar 泛型
https://www.cnblogs.com/poloyy/p/15154196.html
Any Type
https://www.cnblogs.com/poloyy/p/15158613.html
Union
https://www.geek-share.com/detail/2840537300.html
Optional
https://www.geek-share.com/detail/2840542100.html