python协程函数

协程函数

实例:

def menu(x):
    print("welcome %s to shaxian restaurant" % x)
    men_list = []
    while True:
        print(men_list)
        food = yield men_list
        print("%s start to eat %s" % (x, food))
        men_list.append(food)


g = menu('张三')
next(g)
g.send('包子') # 将'包子'传给yield ,然后赋值给了food,然后从上次暂停的位置接着执行代码,直到又到下一个yield
g.send('饺子')
g.send('牛肉面')

g.send与next(g)的区别是:

1.如果函数内yield是表达式形式,那么必须先next(g)

2.二者的共同之处都是可以让函数在上一次暂停的位置继续运行,不一样的地方在于send在触发下一次代码的执行时,会顺便给yield传一个值

如果不想写next的初始化,而直接调用send,可以选择加个装饰器

def happy(fuc):
    def f1(*args, **kwargs):
        res = fuc(*args, **kwargs)
        next(res)      #让函数调用时自动初始化next
        return res
    return f1


@happy
def menu(x):
    print("welcome %s to shaxian restaurant" % x)
    men_list = []
    while True:
        print(men_list)
        food = yield men_list
        print("%s start to eat %s" % (x, food))
        men_list.append(food)


g = menu('张三')

g.send('包子')        
# 将'包子'传给yield ,然后赋值给了food,然后从上次暂停的位置接着执行代码,直到又到下一个yield
g.send('饺子')
g.send('牛肉面')

 

posted on 2018-08-22 23:14  Messiless  阅读(97)  评论(0编辑  收藏  举报