python 协程二

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

https://blog.csdn.net/s695811494/article/details/112097536

 

你可能感兴趣的:(python,并发编程,python,并发编程)