def consumer():
n = 0
while True:
n = yield n
n = n - 1
print "del. 1"
def producer(consumer):
n = 0
next(consumer) #equal to consumer.next() or consumer.send(None)
while n < 6:
n = n + 2
print "add 2, now is %d" %(n)
n = consumer.send(n)
print 'now is %d' %(n)
consumer.close()
producer(consumer())
打印出来的结果是:
add 2, now is 2
del. 1
now is 1
add 2, now is 3
del. 1
now is 2
add 2, now is 4
del. 1
now is 3
add 2, now is 5
del. 1
now is 4
add 2, now is 6
del. 1
now is 5
add 2, now is 7
del. 1
now is 6
用一种十分不恰当的说法解释下上面中这个程序
函数producer先执行next启动生成器,生成器函数(对象)开始执行,执行到n = yield n语句时,我们需要先执行yield n,并且yield n语句的返回值赋值给n。执行yield n的结果貌似使得next(consumer) 函数返回,且函数的返回值为yield n中的n值,此时函数向下执行,进入while循环,在循环中执行到consumer.send(n),这样貌似我们又进入了函数(生成器对象)consumer中了,此时函数中的yield n语句返回,返回值是consumer.send(n)中的n值,故n = yield n中赋值语句左端的变量n得到赋值,程序继续向下执行,再次遇到n = yield n语句,如此循环往复。
其实我们使用contextlib模块,也是利用了yield的这个特性