Python with yield语句

1.with 语句

  语法: with expression as variable

  需要引入一个上下文管理协议,实现的方法是为一个类定义 __enter__() 和 __exit__() 方法, 在执行with block中的语句时之前执行 __enter__方法中的代码,最后不管执行到哪里出现异常, 都会之心__exit__() 中的代码。

  可以用来简化 try / finally 语句。 变量的值是__enter__()的返回值,如果没有这个部分,则返回值被忽略。

import sys
class test:
    def __enter__(self):
        print ("executing  __enter__()")
        return "roger"
    def __exit__(self,*args):
        print("executing  __exit__()")
        return True

with test() as t:
    print t

  其中, test类的对象 test() 是给with控制流使用的,因为要调用类中的两个方法,必须使用一个对象。

  经常在文件操作,数据库操作中使用,从而关闭文件和数据库。

2.yield 语句

  参考: http://pyzh.readthedocs.org/en/latest/the-python-yield-keyword-explained.html