with file('test.py','r') as f : print f.readline()
#!encoding:utf-8 class echo : def output(self) : print 'hello world' def __enter__(self): print 'enter' return self #返回自身实例,当然也可以返回任何希望返回的东西 def __exit__(self, exception_type, exception_value, exception_traceback): #若发生异常,会在这里捕捉到,可以进行异常处理 print 'exit' #如果改__exit__可以处理改异常则通过返回True告知该异常不必传播,否则返回False if exception_type == ValueError : return True else: return False with echo() as e: e.output() print 'do something inside' print '-----------' with echo() as e: raise ValueError('value error') print '-----------' with echo() as e: raise Exception('can not detect')
from contextlib import contextmanager @contextmanager def make_context() : print 'enter' try : yield {} except RuntimeError, err : print 'error' , err finally : print 'exit' with make_context() as value : print value
from contextlib import contextmanager from contextlib import nested from contextlib import closing @contextmanager def make_context(name) : print 'enter', name yield name print 'exit', name with nested(make_context('A'), make_context('B')) as (a, b) : print a print b with make_context('A') as a, make_context('B') as b : print a print b class Door(object) : def open(self) : print 'Door is opened' def close(self) : print 'Door is closed' with closing(Door()) as door : door.open()
运行结果:
总结: python有很多强大的特性,由于我们平常总习惯于之前C++或java的一些编程习惯,时常忽略这些好的机制。因此,要学会使用这些python特性,让我们写的python程序更像是python。
以上就是Python基础教程之with、contextlib的实例用法详解的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于Python基础教程之with、contextlib的实例用法详解的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did81819