Python yield关键字

Code example

# coding=utf8
def generator():
    print "This is generator."
    generator_string = "bad"
    while True:
        n = yield generator_string # 悬挂(suspend)在此处,n接收send()函数发送过来的值
        print "generator_string %d" % n
        generator_string = "fine."

def normal_function(gen):
    start_generator_string = gen.next() # 开启生成器,返回yield关键字后的变量
    print start_generator_string # 打印返回的变量
    n = 0
    while n < 5:
        n = n + 1
        print "normal_function %d" % n
        generator_string = gen.send(n) # 向yield关键的地方发送n, 并返回yield关键字后面的变量
        print generator_string
    gen.close() # 关闭

if __name__ == '__main__':
    gen = generator() # 此处并不会运行函数(生成器)
    print "generator function finished."
    normal_function(gen)

'''
运行结果:

lee@localhost:tornado-test$ python temp.py 
generator function finished.
This is generator.
bad
normal_function 1
generator_string 1
fine.
normal_function 2
generator_string 2
fine.
normal_function 3
generator_string 3
fine.
normal_function 4
generator_string 4
fine.
normal_function 5
generator_string 5
fine.
'''

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部