python学习笔记 with语句

来源:互联网 发布:桌面日历记事本软件 编辑:程序博客网 时间:2024/06/05 09:09
理解Python中的with语句:

有一些任务可能实现需要设置,时候需要做清理工作,对于这种场景,Python的with语句是一种非常好的处理方式,一个好的例子是文件处理,你需要获取一个文件句柄,从文件中读取数据,操作文件,最后关闭文件句柄。如果不用with语句的代码就是如下方法:

file=open('test.txt')
data=file.read()
file.close()

这里就存在两个问题,一个是文件可能忘记关闭文件句柄,而是文件读取可能出现异常没有处理。于是就产生如下方法:

file=open('test.txt')
try:
data=file.read()
finally:
file.close()

但是无疑这样的代码过于臃肿,于是引入with语句 只需要如下两句即可:

with open('test.txt') as file:
data=file.read()

这样的代码无疑简单易懂,那么with是怎样工作的呢?:基本思想是with所求值的对象必须有一个__enter__() 和__exit__() 方法,紧跟着with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将赋值给as后面的变量。当with后面的代码块全部被执行完毕后,将调用前面返回对象的__exit__()方法参照如下:

#!/usr/bin/env/python
#-*-coding:utf-8-*-
#with_example.py
 
class 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
in __enter__()
sample:foo
in __exit__()

可见首先 

1:get__sample()运行得到一个为Sample类的对象实例

2:这个对象的 __enter__()方法被调用 返回一个字符串 'foo' 

3:然后将这个字符串赋值给 sample 这个变量,

4:现在sample保存了'foo' 这个字符串,继续运行 print 'sample',sample 这个对象 

5:最后调用最开始得到的Sample对象实例的 __exit__() 方法 

#!/usr/bin/env/python
#-*-coding:utf-8-*-
#with_example2.py
 
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。由图中可以看见 type,value,trace的用途都是为了异常所用。

0 0
原创粉丝点击