Python with语句上下文管理器两种实现方法分析
本文实例讲述了Pythonwith语句上下文管理器。分享给大家供大家参考,具体如下:
在编程中会经常碰到这种情况:有一个特殊的语句块,在执行这个语句块之前需要先执行一些准备动作;当语句块执行完成后,需要继续执行一些收尾动作。例如,文件读写后需要关闭,数据库读写完毕需要关闭连接,资源的加锁和解锁等情况。
对于这种情况python提供了上下文管理器(ContextManager)的概念,可以通过上下文管理器来定义/控制代码块执行前的准备动作,以及执行后的收尾动作。
一、为何使用上下文管理器
1、不使用上下文管理器的情况
通过try...finally语句执行异常处理和关闭句柄的动作。
logger=open("log.txt","w") try: logger.write('Hello') logger.write('World') finally: logger.close() printlogger.closed
2、使用上下文管理器
默认文件Python的内置file类型是支持上下文管理协议的。
使用上下文管理器with使得依据精简了很多。
withopen("log.txt","w")aslogger: logger.write('Hello') logger.write('World') printlogger.closed
二、实现上下文管理器实现上下文管理器有两种方式实现。方法一:类实现__enter__和__exit__方法。方法二:contextlib模块装饰器和生成器实现。
下面我们通过两种方法分别实现一个自定义的上下文管理器。
1、方法一:通过类实现__enter__和__exit__方法
classFile(object): def__init__(self,file_name,method): self.file_obj=open(file_name,method) def__enter__(self): returnself.file_obj def__exit__(self,type,value,traceback): self.file_obj.close() withFile('demo.txt','w')asopened_file: opened_file.write('Hola!')
实现__enter__和__exit__方法后,就能通过with语句进行上下文管理。
a、底层都发生了什么?
1、with语句先暂存了File类的__exit__方法,然后它调用File类的__enter__方法。
2、__enter__方法打开文件并返回给with语句,打开的文件句柄被传递给opened_file参数。
3、with语句调用之前暂存的__exit__方法,__exit__方法关闭了文件。
b、异常处理
关于异常处理,with语句会采取哪些步骤。
1.它把异常的type,value和traceback传递给__exit__方法
2.它让__exit__方法来处理异常
3.如果__exit__返回的是True,那么这个异常就被忽略。
4.如果__exit__返回的是True以外的任何东西,那么这个异常将被with语句抛出。
异常抛出
#异常抛出,_exit__返回的是True以外的任何东西,那么这个异常将被with语句抛出 classFile(object): def__init__(self,file_name,method): self.file_obj=open(file_name,method) def__enter__(self): returnself.file_obj def__exit__(self,type,value,traceback): self.file_obj.close() print"type:",type print"value:",value print"traceback:",traceback withFile('demo.txt','w')asopened_file: opened_file.undefined_function('Hola!') #output================================================ #type:#value:'file'objecthasnoattribute'undefined_function' #traceback: #opened_file.undefined_function('Hola!') #AttributeError:'file'objecthasnoattribute'undefined_function'
异常忽略:
#异常忽略,__exit__返回的是True,那么这个异常就被忽略。 classFile(object): def__init__(self,file_name,method): self.file_obj=open(file_name,method) def__enter__(self): returnself.file_obj def__exit__(self,exception_type,exception_value,traceback): print("Exceptionhasbeenhandled") self.file_obj.close() returnTrue withFile('demo.txt','w')asopened_file: opened_file.undefined_function('Hola!') #output================================== #Exceptionhasbeenhandled
2、方法二:contextlib模块装饰器和生成器实现
这种方式实现更优雅,我个人更喜欢这种方式。
yield之前的代码由__enter__方法执行,yield之后的代码由__exit__方法执行。本质上还是__enter__和__exit__方法。
#coding:utf-8 importcontextlib @contextlib.contextmanager defmyopen(filename,mode): f=open(filename,mode) try: yieldf.readlines() exceptExceptionase: printe finally: f.close() if__name__=='__main__': withmyopen(r'c:\ip2.txt','r')asf: forlineinf: printline
3、with语句上多个下文关联
直接通过一个with语句打开多个上下文,即可同时使用多个上下文变量,而不必需嵌套使用with语句。
classFile(object): def__init__(self,file_name,method): self.file_obj=open(file_name,method) def__enter__(self): returnself.file_obj def__exit__(self,exception_type,exception_value,traceback): self.file_obj.close() returnTrue withFile('demo.txt','w')asf1,File('demo.txt','w')asf2: printf1,f2 #Output============================#
更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《PythonSocket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。