Python - typing 模块 —— 类型别名
前言
typing 是在 python 3.5 才有的模块
前置学习
Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html
常用类型提示
https://www.cnblogs.com/poloyy/p/15150315.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 vector scale(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.cnblogs.com/poloyy/p/15154008.html
TypeVar 泛型
https://www.cnblogs.com/poloyy/p/15154196.html
Any Type
https://www.cnblogs.com/poloyy/p/15158613.html
Union
https://www.cnblogs.com/poloyy/p/15170066.html