深入浅析python with语句简介
with语句是从Python2.5开始引入的一种与异常处理相关的功能(2.5版本中要通过from__future__importwith_statement导入后才可以使用),从2.6版本开始缺省可用(参考What'snewinPython2.6?中with语句相关部分介绍)。with语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的“清理”操作,释放资源,比如文件使用后自动关闭、线程中锁的自动获取和释放等。
术语
要使用with语句,首先要明白上下文管理器这一概念。有了上下文管理器,with语句才能工作。
在python中读写操作资源,最后需要释放资源。可以使用try…finally结构实现资源的正确释放,python提供了一个with语句能更简便的实现释放资源。
1.python像文件的操作open等已经可以直接使用with语句
2.可以自定义一个支持with语句对象
3.使用contextlib也可以使用with语句对象
4.针对需要close操作的对象with的使用
示例代码中有4种使用标注
#自定义支持with语句的对象
classDummyRes:
def__init__(self,tag):
self.tag=tag
def__enter__(self):
print("Enter>>>{}".format(self.tag))
returnself
def__exit__(self,exc_type,exc_value,exc_tb):
print("Exit<<<{}".format(self.tag))
ifexc_tbisNone:
print("ExitwithoutException{}".format(self.tag))
returnFalse
else:
print("ExitwithException{}".format(self.tag))
returnTrue
#支持closing上下文with语句对象
classClosing:
def__init__(self,thing):
self.thing=thing
def__enter__(self):
returnself
def__exit__(self,exc_type,exc_value,exc_tb):
self.thing.close()
classClosingDemo:
def__init__(self):
self.acquire()
defacquire(self):
print("AcquireRES")
defclose(self):
print("CloseRES")
fromcontextlibimportcontextmanager
classContextDemo:
def__init__(self):
print("ContextDemoinit")
raiseException
print("ContextDemoinit")
defprint(self):
print("ContextDemoprint1")
#raiseException
print("ContextDemoprint2")
defclose(self):
print("ContextDemoclose")
defcontext_demo():
print("contextdemoin")
raiseException
print("contextdemoout")
@contextmanager
defdemo():
print("AllocateResoures")
try:
yieldcontext_demo
finally:
print("raiseexception")
#yield"***contextmanagerdemo***"
print("FreeResoures")
if__name__=="__main__":
#1.使用with语句(自动关闭文件)
withopen("test.txt","w")asf:
f.write("writetest")
#2.自动定义with语句
withDummyRes("test")asres:
print("Withbody1")
raiseException
print("Withbody2")
#3.利用contextlib定义with语句
withdemo():
print("excdemo")
#4.closing上下文(适合有close操作的情况)
withClosing(ClosingDemo()):
print("UseResoures")
总结
以上所述是小编给大家介绍的pythonwith语句简介,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!