http://blog.csdn.net/azhao_dn/article/details/7659276
一 with
python中的with的作用是自动释放对象,即使对象在使用的过程中有异常抛出。可以使用with的类型必须实现__enter__ __exit__。我的理解是=try...finally{},在finally中调用了释放函数。
[类似与CSharp中的using(){}关键字,用来自动确保调用对象的dispose()方法,即使对象有异常抛出。C#中可以使用using{}的对象必须已经实现了IDispose接口。]
with open( " myfile.txt " ) as f:
for line in f:
print (line)
f.readline() # f is already clean up here, here will meet ValueError exception
TestWith()
在with语句执行完以后,f对象马上就被释放了。所以下面在调用f.readline()会出错。
二 with + try...except
既能让对象自动释放,又包含了异常捕获的功能。
def __init__ (self, filename):
self.filename = filename
self.f = None
def __enter__ (self):
try :
f = open(self.filename, ' r ' )
content = f.read()
return content
except IOError as e:
print (e)
def __exit__ (self, type, value, traceback):
if self.f:
print ( ' type:%s, value:%s, traceback:%s ' % (str(type), str(value), str(traceback)))
self.f.close()
def TestWithAndException():
with controlled_execution( " myfile.txt " ) as thing:
if thing:
print (thing)
# TestWithAndException()
with从Python 2.5就有,需要from __future__ import with_statement。自python 2.6开始,成为默认关键字。
也就是说with是一个控制流语句,跟if/for/while/try之类的是一类的,with可以用来简化try finally代码,看起来可以比try finally更清晰。这里新引入了一个"上下文管理协议"context management protocol,实现方法是为一个类定义__enter__和__exit__两个函数。
with expresion as variable的执行过程是,首先执行__enter__函数,它的返回值会赋给as后面的variable,想让它返回什么就返回什么,只要你知道怎么处理就可以了,如果不写as variable,返回值会被忽略。
然后,开始执行with-block中的语句,不论成功失败(比如发生异常、错误,设置sys.exit()),在with-block执行完成后,会执行__exit__函数。
这样的过程其实等价于:
- try:
- 执行 __enter__的内容
- 执行 with_block.
- finally:
- 执行 __exit__内容
我们可以自己实现一个例子:
- import sys
- class test:
- def __enter__(self):
- print("enter")
- return 1
- def __exit__(self,*args):
- print("exit")
- return True
- with test() as t:
- print("t is not the result of test(), it is __enter__ returned")
- print("t is 1, yes, it is {0}".format(t))
- raise NameError("Hi there")
- sys.exit()
- print("Never here")
1、t不是test()的值,test()返回的是"context manager object",是给with用的。t获得的是__enter__函数的返回值,这是with拿到test()的对象执行之后的结果。t的值是1.
2、__exit__函数的返回值用来指示with-block部分发生的异常是否要re-raise,如果返回False,则会re-raise with-block的异常,如果返回True,则就像什么都没发生。
一 with
python中的with的作用是自动释放对象,即使对象在使用的过程中有异常抛出。可以使用with的类型必须实现__enter__ __exit__。我的理解是=try...finally{},在finally中调用了释放函数。
[类似与CSharp中的using(){}关键字,用来自动确保调用对象的dispose()方法,即使对象有异常抛出。C#中可以使用using{}的对象必须已经实现了IDispose接口。]
with open( " myfile.txt ") as f:
for line in f:
print (line)
f.readline() # f is already clean up here, here will meet ValueError exception
TestWith()
在with语句执行完以后,f对象马上就被释放了。所以下面在调用f.readline()会出错。
二 with + try...except
既能让对象自动释放,又包含了异常捕获的功能。
def __init__(self, filename):
self.filename = filename
self.f = None
def __enter__(self):
try:
f = open(self.filename, ' r ')
content = f.read()
return content
except IOError as e:
print (e)
def __exit__(self, type, value, traceback):
if self.f:
print ( ' type:%s, value:%s, traceback:%s ' % (str(type), str(value), str(traceback)))
self.f.close()
def TestWithAndException():
with controlled_execution( " myfile.txt ") as thing:
if thing:
print(thing)
# TestWithAndException()