

说明
1、先调用函数获取生成器对象,再调用next方法或send(None)方法打开coroutine。
2、函数执行到yield位置,返回yield后挂起,把控制流交回主线程。再调用send法时,可以传输数据并激活协程。
继续执行到最后或下一个yield语句。
实例
"""
# BEGIN CORO_AVERAGER_TEST
    >>> coro_avg = averager()  # <1>
    >>> next(coro_avg)  # <2>
    >>> coro_avg.send(10)  # <3>
    10.0
    >>> coro_avg.send(30)
    20.0
    >>> coro_avg.send(5)
    15.0
# END CORO_AVERAGER_TEST
"""
def averager():
    total = 0.0
    count = 0
    average = None
    while True:  # <1>
        term = yield average  # <2>
        total += term
        count += 1
        average = total/count以上就是python coroutine的运行过程,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
收藏 | 0点赞 | 0打赏