python 協程二
阿新 • • 發佈:2021-01-03
1 使用協程實現移動均值函式
>>> from inspect import getgeneratorstate as gs >>> def mean_coroutine(): ... total = 0 ... count = 0 ... average = None ... while True: ... val = yield average ... total += val ... count += 1 ... average = total / count ... >>> avg_cor=mean_coroutine() >>> gs(avg_cor) 'GEN_CREATED' >>> next(avg_cor) >>> avg_cor.send(10) 10.0 >>> avg_cor.send(20) 15.0 >>> avg_cor.send(30) 20.0
2 使用裝飾器實現一個預激的協程
>>> def decorator(func): ... def primer(*args,**kwarg): ... cor = func(*args,**kwarg) ... next(cor) ... return cor ... return primer ... >>> @decorator ... def mean_coroutine(): ... total = 0 ... count = 0 ... average = None ... while True: ... val = yield average ... total += val ... count += 1 ... average = total / count ... >>> from inspect import getgeneratorstate as gs >>> avg_cor = mean_coroutine() >>> gs(avg_cor) 'GEN_SUSPENDED' >>> avg_cor.send(1) 1.0 >>> avg_cor.send(3) 2.0 >>> avg_cor.send(5) 3.0