Python入门-程序结构扩展
deque双端队列
#双端队列,就是生产消费者模式,依赖collections模块 from collections import deque def main(): info = deque(("hello", "word")) # 内部是序列 info.append(("百度一下")) # 右边添加数据 info.appendleft("www.baidu.com") # 左边添加数据 print("【队列数据】:",info) print("----开始弹出数据------") print(info.pop()) print(info.popleft()) print("------弹出完毕--------") print(info) main() """ 【队列数据】: deque(['www.baidu.com', 'hello', 'word', '百度一下']) ----开始弹出数据------ 百度一下 www.baidu.com ------弹出完毕-------- deque(['hello', 'word']) """
heapq堆
# 堆是基于二叉树实现的。最大特点是里面的数据是有序的,同时是中序遍历获取 # 堆中存放的内容,基于二叉树存储,可以方便的实现排序后的数据获取 import heapq def f(): data = list(range(10)) print("定义列表:", data) heapq.heapify(data) # 基于迭代对象创建一个堆 heapq.heappush(data, 0)# 进行数据的保存 print("原始堆数据:", data) #自动对原列表进行更新 print("获取堆中前2个最大数据:", heapq.nlargest(2, data)) print("获取堆中前3个最xiao数据:", heapq.nsmallest(3, data)) f() """ 定义列表: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 原始堆数据: [0, 0, 2, 3, 1, 5, 6, 7, 8, 9, 4] 获取堆中前2个最大数据: [9, 8] 获取堆中前3个最xiao数据: [0, 0, 1] """
enum枚举
# 定义可用数据的范围 import enum @enum.unique #使用装饰器,防止数据重复,如果重复,运行就会报错:duplicate values class Color_Base(enum.Enum): # 必须强制继承父类 red = 0 green = 1 blue = 2 if __name__ == '__main__': c = Color_Base.blue # 直接通过枚举,获取所需要的一个对象 print("枚举对象名称:{},枚举对象类型:{}".format(c.name, c.value)) #枚举对象名称:blue,枚举对象类型:2
上下文管理with
自定义实现
class Message: class Connect: def build(self): print("开始连线好友。。。") return True def close(self): print("已经断开消息链接。") def send(self, info): try: conn = Message.Connect() if conn.build(): print("正在发送消息:", info) else: print("出问题了。") except Exception as e: print("消息延迟:", e) finally: conn.close() print("=====通话完成====") if __name__ == '__main__': m = Message() m.send("百度一下") m.send("www.baidu.com") """ 开始连线好友。。。 正在发送消息: 百度一下 已经断开消息链接。 =====通话完成==== 开始连线好友。。。 正在发送消息: www.baidu.com 已经断开消息链接。 =====通话完成==== """
with实现
# with关键词,管理上下文,上下文开启,上下文退出 class Message: class Connect: def build(self): print("开始连线好友。。。") return True def close(self): print("已经断开消息链接。") def __enter__(self): print("=====with语句开始执行=====") self.conn = Message.Connect() if not self.conn.build(): print("建立通话失败。") return self def __exit__(self, exc_type, exc_val, exc_tb): print("=====with语句结束了=======") self.conn.close() def send(self, info): print("正在发送消息:", info) if __name__ == '__main__': with Message() as me: me.send("谷歌") me.send("www.google.com") """ =====with语句开始执行===== 开始连线好友。。。 正在发送消息: 谷歌 正在发送消息: www.google.com =====with语句结束了======= 已经断开消息链接。 """
上下文管理contextlib
# 使用contextlib模块,进行上下文管理 from contextlib import contextmanager class Message: def send(self, info): print("消息发送中") @contextmanager def message_wrap(): class __Connect: def build(self): print("connect:建立网络连接") return False def close(self): print("connect:关闭网络连接") try: conn = __Connect() if conn.build(): yield Message() #获取下一个实例 else: yield None except Exception as e: print("except连接异常:", e) finally: conn.close() if __name__ == '__main__': with message_wrap() as m: m.send("www.baidu.com") """ connect:建立网络连接 except连接异常: 'NoneType' object has no attribute 'send' connect:关闭网络连接 """
自动关闭功能实现
from contextlib import contextmanager,closing class Connect: def __init__(self): print("connect:开始建立连接") def send(self, info): print("消息发送中") def close(self): print("connect:关闭网络连接") if __name__ == '__main__': with closing(Connect()) as c: #自动关闭功能支持 print("消息发送:www.baidu.com") """ 消息发送:www.baidu.com connect:关闭网络连接 """