python with as用法

with as用途:取代原来的try...finally,主要是用于处理异常

基本语法;with EXPRESSION [ as VARIABLE] WITH-BLOCK 

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

紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量。

当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。

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

 

posted on 2016-03-12 11:22  qmzp  阅读(225)  评论(0编辑  收藏  举报

导航