说明

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电脑。

售后响应及时
7×24小时客服热线
数据备份
更安全、更高效、更稳定
价格公道精准
项目经理精准报价不弄虚作假
合作无风险
重合同讲信誉,无效全额退款