python 基础(十六)生成器用法举例

import  time
def consumer(name):
    print('%s,准备吃包子'%name)
    while True:
        baozi = yield
        print('包子%s来了,被%s吃了'%(baozi,name))
c = consumer('clyde')
c.__next__()  #__next__():调用一次
b = '香菇油菜馅'
c.send(b) #send():把参数发送过去在调用一次

协程

import  time
def consumer(name):
    print('%s,准备吃包子'%name)
    while True:
        baozi = yield
        print('包子%s来了,被%s吃了'%(baozi,name))
c = consumer('clyde')
c.__next__()
def producer(name):
    c = consumer('张三')
    c2 = consumer('的歌')
    c.__next__()
    c2.__next__()
    print('我开始准备做包子了')
    for i in range(10):
        time.sleep(1)
        print('做了一个包子')
        c.send(i)
        c2.send(i)
producer('name')
原文地址:https://www.cnblogs.com/zbvc/p/13132259.html