1. 上下文管理器
__enter__()方法返回资源对象,__exit__()方法处理一些清除资源
如:系统资源:文件、数据库链接、Socket等这些资源执行完业务逻辑之后,必须要关闭资源
#!/usr/bin/python3 #-*- coding:utf-8 -*- class File(object): def __init__(self, filename, mode): self.filename = filename self.mode = mode def __enter__(self): print("entering....") self.f = open(self.filename, self.mode) return self.f def __exit__(self, *args): print("will exit") self.f.close() with File("out.txt", 'w') as f: print("writing....") f.write('hello, python')
entering....
writing....
will exit
2. 使用 @contextmanager
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, test")