1、概念
含有__enter__和__exit__方法的对象就是上下文管理器
2、语法
whith 上下文管理器:
代码块
3、使用场景
只要创建/打开用完需要关闭时就可以用with实现,例如socket、文件读写、数据库连接等
4、第一种实现方式
__enter__() 方法返回资源对象,__exit__() 方法处理一些清除工作。
class WriteIn(object):
def __init__(self, filePath, mode):
self.filePath = filePath
self.mode = mode
def __enter__(self):
self.f = open(self.filePath, self.mode)
return self.f
def __exit__(self, *args):
self.f.close()
# 调用
with WriteIn("./jiekema.txt", "w") as f:
f.write("我是杰克马")
通过@contextmanager装饰器实现上下文管理器
python提供的@contextmanager 装饰器,通过 yield 将函数分割成两部分,yield 之前的语句在 __enter__ 方法中执行,yield 之后的语句在 __exit__ 方法中执行。紧跟在 yield 后面的值是函数的返回值。
from contextlib import contextmanager
@contextmanager
def my_open(path, mode):
f = open(path, mode)
yield f
f.close()
# 调用
with my_open('out.txt', 'w') as f:
f.write("hello_world")
第二段代码等同于第一段代码
class WriteIn(object):
def __init__(self, filePath, data):
self.filePath = filePath
self.data = data
def writeIn(self):
f = open(self.filePath, "w")
try:
f.write(self.data)
except IOError:
print("error")
finally:
f.close()
w = WriteIn("./a.txt", "哈哈")
w.writeIn()
class WriteIn(object):
def __init__(self, filePath, data):
self.filePath = filePath
self.data = data
def writeIn(self):
with open(self.filePath, "w") as f:
f.write(self.data)
w = WriteIn("./a.txt", "哈哈")
w.writeIn()