直接上代码:
#python上下文管理器
#with用法
with open('E:\\DemoTestData\\demo.txt','w') as f:
f.write('hello')
#实现效果:将open返回值给f :然后执行方法
class ContextManager(object):
def __init__(self):
self.entered = '未使用上下文管理器'
print("ddss")
def __enter__(self):
self.entered = '进入上下文管理器'
print(self.entered)
return self
def __exit__(self, exc_type, exc_instance, traceback):
self.entered = '退出上下文管理器'
print("battle")
with ContextManager() as cm:
cm.entered