python generator

加了yield 后 函数返回的是一个generater print(type(atm))
不能直接返回值  返回的是一个迭代器 遍历迭代器即可得到执行结果
类似于异步

def cash_out(amount):
    while(amount>0):
        amount-=100
yield 100
print("cash again!")

atm = cash_out(500)
for i in atm:
    print(i)

模拟异步 yield 接收传入的例子

def consumer(name):
    print("consumer:"+name)
    while True:
        baozi = yield
print("consumer:"+name+":"+str(baozi))


def productor(name):
    c1=consumer("a")
    c2=consumer("b")
    c1.__next__()
    c2.__next__()
    print(name + "开始生产")
    for i in range(10):
        time.sleep(1)
        c1.send(i)
        c2.send(i)

productor("productor")

你可能感兴趣的:(python generator)