yield 表达式形式的应用

import random
foods=['banana','apple','peach','grape','pear']

def deco(func):
    def wrapper(*args,**kwargs):
        g=func(*args,**kwargs)
        next(g)
        return g
    return wrapper

@deco
def eater(name):
    print('%s ready to eat'%name)
    foods_list=[]
    while 1:
        food=yield foods_list
        foods_list.append(food)
        print('%s has eaten %s '%(name,food))

e=eater('Yang')
i=0
while i<10:
    if i == 9:
        print(e.send(random.choice(foods)))
    else:
        e.send(random.choice(foods))
    i+=1

 

posted @ 2017-06-19 19:05  皖心  阅读(153)  评论(0编辑  收藏  举报