yield 生成器例子
1 #!/usr/bin/env python 2 #encoding: utf-8 3 import time 4 def consumer(name): 5 print ('%s 来吃包子了。。。' % (name)) 6 while True: 7 baizi = yield #执行到这会暂停,直到调用next的方法,然后在从这里执行 8 print ("包子 [%s] 来了, 被 [%s] 吃了,,," % (baizi,name)) 9 10 def producer(): 11 c1 = consumer('lys') #生成迭代器 12 c2 = consumer('zhy') 13 c1.__next__() #迭代 14 c2.__next__() 15 for i in range(3): 16 print ('开始重新做包子了,,,') 17 time.sleep(1) 18 print ('做好了2个。来吃吧,,,') 19 c1.send(i) #发送给yied,接收参数 20 c2.send(i) 21 22 producer()