typing 是在 python 3.5 才有的模块
Python 类型提示:https://cloud.tencent.com/developer/article/1864619
https://cloud.tencent.com/developer/article/1866298
可以将复杂一点类型给个别名,这样好用一些
# 别名
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'})
https://www.cnblogs.com/poloyy/p/15153886.html
https://cloud.tencent.com/developer/article/1866297
https://cloud.tencent.com/developer/article/1866293