Python 上下文管理器

上下文管理器

文件读写 的章节,我使用过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()方法。

Python 教程 Python 入门 Python 时间 Python JSON