'''
同步上下文管理器
'''
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,self,conn,print,上下文,def
From: https://www.cnblogs.com/leoshi/p/17275450.html