python中with的意义
来源:互联网 发布:windows安装caffe 编辑:程序博客网 时间:2024/06/06 03:06
with自python2.5就存在了,需要用from __feature__ import with_statement,自2.6开始成为默认的关键字。
with语句是什么?
有一些任务可能需要事先设置,事后做清理工作。对于这种场景,python的with语句提供了一种非常方便的处理方式。一个比较好的例子是文件处理,你需要获取一个文件句柄,从文件中读取数据,然后关闭文件句柄。
如果不使用句柄,代码如下:
file = open("/tmp/foo.txt")data = file.read()file.close()这里有两个问题存在,一个是忘记关闭文件句柄,二是文件读取发生异常时,没有进行任何处理。下面是处理异常的加强版:
file = open("/tmp/foo.txt")try: data = file.read()finally: file.close()虽然这段代码运行良好,但是太冗长了。于是便到了with一展身手的时候了,除了有更优雅的语法,with还可以很好的处理上下文环境所产生的异常,下面是with版本的代码:
with open("/tmp /foo.txt") as file: data = file.read()
while this might look like magic,the way python handles with is more clever than magic。基本思想是with所求值的对象必须有一个__enter()__方法和一个__exit()__方法。紧跟在with后面的语句在被求值后,返回对象的__enter()__方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部执行完之后,将调用前面返回对象的__exit()__方法。当然,如果没有as 及其后面的变量也是合乎语法的。下面的例子能够更好的说明with是如何工作的:
#!/usr/bin/env python# with_example01.pyclass Sample: def __enter__(self): print "In __enter__()" return "Foo" def __exit__(self, type, value, trace): print "In __exit__()"def get_sample(): return Sample()with get_sample() as sample: print "sample:", sample
bash-3.2$ ./with_example01.pyIn __enter__()sample: FooIn __exit__()
正如你看到的,代码的执行顺序为:
1、__enter()__方法被执行
2、__enter()__方法返回的值:这个例子中是"Foo",赋值给变量"sample"
3、执行代码块,打印变量sample
4、__exit()__方法被执行
with的真正强大之处在于可以处理异常,可能你已经注意到Smaple类中的__exit__方法中有三个参数,val,type和trace。这些参数在处理异常的时候相当有用,我们来修改一下代码,来查看一下他们的具体工作:
#!/usr/bin/env python# with_example02.pyclass Sample: def __enter__(self): return self def __exit__(self, type, value, trace): print "type:", type print "value:", value print "trace:", trace def do_something(self): bar = 1/0 return bar + 10with Sample() as sample: sample.do_something()
bash-3.2$ ./with_example02.pytype: <type 'exceptions.ZeroDivisionError'>value: integer division or modulo by zerotrace: <traceback object at 0x1004a8128>Traceback (most recent call last): File "./with_example02.py", line 19, in <module> sample.do_somet hing() File "./with_example02.py", line 15, in do_something bar = 1/0ZeroDivisionError: integer division or modulo by zero
实际上,在with后面的代码抛出异常时,__exit()__方法被执行。正如例子中所示,异常抛出时,与之关联的type,value和strack trace传给__exit()__方法,因此抛出的ZeroDivisionError异常被打印出来。当然,在开发库的过程中,清理资源,关闭文件等等操作都可以放到__exit()__方法中去。如果__exit()__方法的返回值用来指示with_block部分发生的异常是否要re-raise,如果返回False,则会re-raise with-block中的异常,如果返回True,则会像什么都没发生。如下例:
class Sample: def __enter__(self): return self def __exit__(self, type, value, trace): print "type:", type print "value:", value print "trace:", trace return True<span style="white-space:pre"></span>(1) def do_something(self): bar = 1/0 return bar + 10 with Sample() as sample: sample.do_something()print 'aaa'输出如下:
type: <type 'exceptions.ZeroDivisionError'>value: integer division or modulo by zerotrace: <traceback object at 0x01BC60A8>aaa如果将代码中(1),改成return False或者,删除返回值,则输出为:
bash-3.2$ ./with_example02.pytype: <type 'exceptions.ZeroDivisionError'>value: integer division or modulo by zerotrace: <traceback object at 0x1004a8128>Traceback (most recent call last): File "./with_example02.py", line 19, in <module> sample.do_somet hing() File "./with_example02.py", line 15, in do_something bar = 1/0ZeroDivisionError: integer division or modulo by zero
- python中with的意义
- python中with as 语句的作用以及意义
- with do的意义
- python中__name__的意义以及作用
- python中self意义
- python中with的用法
- python 中with的使用
- python 中with的用法
- Python中With的用法
- Python中with的运行机制
- python中with的用法
- Python中with的用法
- python中with的用法
- python前两行的意义
- python的类中变量、函数的特殊命名--意义
- Python中关于下划线的标识符的意义
- Python - "print()"函数 中 "%" 后面字母的意义
- 浅析Python中“if __name__ == __main__”的意义
- Clearwater IMS All-in-one环境搭建指导书
- 计算机网络
- Hadoop 的HA高可集群用性
- 最新123家App换量合作名单
- Clearwater IMS All-in-one环境搭建指导书
- python中with的意义
- 基于Lucence的同义词分词器
- 555555555
- Linux学习笔记之基本命令三(Bash Shell)
- hibernate基于连接表的多对多单向关联
- NYOJ 完全平方数的个数
- 愿我在学习的路上百折不挠无怨无悔
- 不能访问windows 上mysql服务器
- 帝国网站管理系统之网站迁移教程