You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
>>> class A:
def __enter__(self):
print 'in enter'
def __exit__(self, e_t, e_v, t_b):
print 'in exit'
>>> with A() as a:
print 'in with'
in enter
in with
in exit
python中with可以明显改进代码友好度
with 语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的“清理”操作,释放资源,比如文件使用后自动关闭、线程中锁的自动获取和释放等
假设要对一个文件进行操作
而如果我们用try catch finally
代码显得没那么友好
with 语句的执行过程
我们自己的类也可以使用with, 只要给这个类增加两个函数__enter__, __exit__即可:
python库中还有一个模块contextlib,使你不用构造含有__enter__, __exit__的类就可以使用with:
The text was updated successfully, but these errors were encountered: