在 文件读写 的章节,我使用过with open操作文件,让文件对象实现了自动释放资源。我们也能自定义上下文管理器,通过__enter__()和__exit__()这两个魔术方法。
class x():
# with as 开始调用
def __enter__(self):
print('with as started')
# with as 结束调用 | exc_type, exc_value, traceback 异常信息
def __exit__(self,exc_type,exc_value,traceback):
print('with as stoped')
>>> with x() as x:
>>> pass
'with as started'
'with as stoped'
open就是利用这个特性,在__exit__中执行了close()方法。