Auth: 王海飞
Data:2018-06-15
Email:779598160@qq.com
github:https://github.com/coco369/knowledge
代码:
import sys
def simple_coroutine(a):
print('-> start')
b = yield a
print('-> recived', a, b)
c = yield a + b
print('-> recived', a, b, c)
sc = simple_coroutine(5)
next(sc)
try:
sc.send(6) # 5, 6
sc.send(7) # 5, 6, 7
except StopIteration as e:
sys.exit()
def averager():
total = 0.0
count = 0
avg = None
while True:
num = yield avg
total += num
count += 1
avg = total/count
# run
ag = averager()
# 预激协程
print(next(ag)) # None
print(ag.send(10)) # 10
print(ag.send(20)) # 15