python语法31[with来自动释放对象]

 

一 with

python中的with的作用是自动释放对象,即使对象在使用的过程中有异常抛出。可以使用with的类型必须实现__enter__ __exit__。我的理解是=try...finally{},在finally中调用了释放函数。

[类似与CSharp中的using(){}关键字,用来自动确保调用对象的dispose()方法,即使对象有异常抛出。C#中可以使用using{}的对象必须已经实现了IDispose接口。]

 

def  TestWith():
  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

既能让对象自动释放,又包含了异常捕获的功能。

class  controlled_execution(object):
    
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()

 

 

参考:

http://jianpx.javaeye.com/blog/505469

你可能感兴趣的:(python)