上下文管理
上下文构造
- 调用方式
with xxxx as xxx:
do.....
对象形式
__enter__
__exit__
class Open:
def __init__(self):
pass
def __enter__(self, file):
return f = open(file, 'w')
def __exit__(self):
f.close()
return
with custom_open('file') as f:
contents = f.read()
装饰器形式
contextlib
contextlib.contextmanager
from contextlib import contextmanager
@contextmanager
def custom_open(filename):
f = open(filename)
try:
yield f
finally:
f.close()
with custom_open('file') as f:
contents = f.read()
如何选取:
- 需要处理的逻辑负责,代码量大的使用类包装
- 需要处理的逻辑简单,代码量小的使用装饰器