Python协程

把yield视作控制流程的方式--------------Python协程

一个简单的协程:

def simple_coroutine():
    print('-> coroutine started')
    x=yield
    print('-> coroutine received:',x)

>>>my_coro=simple_coroutine()
>>>next(my_coro)
-> coroutine started
>>>my_coro.send(42)
-> coroutine received:42
Traceback (most recent call last):
    ...
StopIteration

解释:

1.调用simple_coroutine()函数,返回生成器对象

2.调用next()函数,启动生成器,在yield语句出暂停

3.传送42,yield表达式会计算出52,然后一直运行到下一个yield表达式,或者终止

4.控制权流动到定义体末尾,生成器抛出StopIteration异常

一个稍微复杂的案例:

使用协程计算移动平均

def averager():
    total=0.0
    count=0
    average=None
    while True:
        term=yield average
        total+=term
        count+=1
        average=total/count

>>>coro_avg=averager()
>>>next(coro_avg)
>>>coro_avg.send(10)
10.0
>>>coro_avg.send(30)
20.0
>>>coro_avg.send(5)
15.0

装饰器------自动预激协程的好方法

from functools import wraps
def coroutine(func):
    @wraps(func):
    def primer(*args,**kwargs):
        gen=func(*args,**kwargs)
        next(gen)
        return gen
    return primer

 

posted @ 2020-08-29 16:34  猫七的blog  阅读(109)  评论(0编辑  收藏  举报