'''
同步上下文管理器
'''
import time
class ContextManager:
def __init__(self):
self.conn = None
def action(self):
return self.conn
def __enter__(self): # 链接数据库
print("开始连接")
time.sleep(1)
self.conn = "OK"
return self
def __exit__(self, exc_type, exc, tb): # 关闭数据库链接
print("关闭连接")
self.conn = "CLOSE"
def main():
with ContextManager() as cm:
result = cm.action()
print(result)
main()
[Python]同步上下文管理
发布时间 2023-03-31 10:32:55作者: LeoShi2020