博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python with as的用法
阅读量:4457 次
发布时间:2019-06-08

本文共 2202 字,大约阅读时间需要 7 分钟。

以下为转载https://www.cnblogs.com/DswCnblog/p/6126588.html

with。。as。。一个使用场景是文件处理,你需要获取一个文件句柄,从文件中读取数据,然后关闭文件句柄。

普通的文件处理如下:

1 file = open("/tmp/foo.txt")2 data = file.read()3 file.close()#文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源,并且操作系统同一时间能打开的文件数量也是有限的

由于文件读写时都有可能产生IOError,一旦出错,后面的f.close()就不会调用。所以,为了保证无论是否出错都能正确地关闭文件,我们可以使用try ... finally来实现:

1 file = open("/tmp/foo.txt")2 try:3     data = file.read()4 finally:5     file.close()

但是还有一个更简洁的实现,就是用with as

1 with open("/tmp/foo.txt") as file:2     data = file.read()

with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。

1 class Sample: 2     def __enter__(self): 3         print "In __enter__()" 4         return "Foo" 5   6     def __exit__(self, type, value, trace): 7         print "In __exit__()" 8   9 def get_sample():10     return Sample()11  12 with get_sample() as sample:13     print "sample:", sample

运行如下:

1 In __enter__()2 sample: Foo3 In __exit__()

运行过程:

1. __enter__()方法被执行,返回的对象赋值给变量'sample'

3. 执行代码块,打印变量"sample"的值为 "Foo"

4. __exit__()方法被调用

with真正强大之处是它可以处理异常。可能你已经注意到Sample类的__exit__方法有三个参数- val, type 和 trace。 这些参数在异常处理中相当有用。我们来改一下代码,看看具体如何工作的。

class 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 + 10 with Sample() as sample:    sample.do_something()

这个例子中,with后面的get_sample()变成了Sample()。这没有任何关系,只要紧跟with后面的语句所返回的对象有__enter__()和__exit__()方法即可。此例中,Sample()的__enter__()方法返回新创建的Sample对象,并赋值给变量sample。

代码执行后:

1 bash-3.2$ ./with_example02.py 2 type: 
3 value: integer division or modulo by zero 4 trace:
5 Traceback (most recent call last): 6 File "./with_example02.py", line 19, in
7 sample.do_something() 8 File "./with_example02.py", line 15, in do_something 9 bar = 1/010 ZeroDivisionError: integer division or modulo by zero

实际上,在with后面的代码块抛出任何异常时,__exit__()方法被执行。正如例子所示,异常抛出时,与之关联的type,value和stack trace传给__exit__()方法,因此抛出的ZeroDivisionError异常被打印出来了。开发库时,清理资源,关闭文件等等操作,都可以放在__exit__方法当中。

因此,Python的with语句是提供一个有效的机制,让代码更简练,同时在异常产生时,清理工作更简单。

 

转载于:https://www.cnblogs.com/saolv/p/8452030.html

你可能感兴趣的文章
一条shell统计代码行数
查看>>
[转]json+JSONObject+JSONArray 结合使用
查看>>
EasyNVR无插件直播服务器软件接口调用返回“Unauthorized”最简单的处理方式
查看>>
POSt 提交参数 实体 和字符串
查看>>
Linux网络故障排查
查看>>
零崎的朋友很多Ⅰ(100)[完全背包]
查看>>
解决ubuntu下rar解压缩乱码
查看>>
hibernate处理null 时提示:Property path [...] does notreference a collection
查看>>
SpringMVC3.2+JPA使用注解的方式环境搭建
查看>>
用JS获取Html中所有图片文件流然后替换原有链接
查看>>
lua与C++的绑定
查看>>
java reflect反射调用方法invoke
查看>>
FUSE文件系统
查看>>
MySQL- 字符集的设置
查看>>
CTSC2014 && 洛谷P4503 企鹅QQ
查看>>
(转)android常见问题之jni读取assets资源文件(附源码)
查看>>
分页插件
查看>>
OAuth 开放授权 Open Authorization
查看>>
Mac在PATH中永久添加路径
查看>>
【知了堂学习笔记】java 自定义异常
查看>>