python coroutine
python coroutine
前言
OOAD课程是用python教的,其中涉及到大量的python语法糖,老师也算是手把手教如何写出OO的python,但一个学期没听课只能期末补一补。
Coroutines
Coroutines are similar to generators with a few differences. The main differences are:
- generators are data producers generators制造数据
- coroutines are data consumers coroutines消费数据
来看第一个代码示例,通过send()接收数据,然后进行比对,找出含有关键字的数据并打印。
def grep(pattern):
print("Searching for", pattern)
while True:
line = (yield)
if pattern in line:
print(line)
search = grep('coroutine')
next(search)
# Output: Searching for coroutine
search.send("I love you")
search.send("Don't you love me?")
search.send("I love coroutines instead!")
很明显我们可以看到,yield关键字在这里已经从返回数据的变为接收数据的。也就是,Python的yield
不但可以返回一个值,它还可以接收调用者发出的参数。
在中文里,coroutine对应的是协程,但是显然老师的重点不是什么同步异步,而是yield,以及coroutine和subprogram的区别。
Subprogram vs Coroutine, is (programming) a piece of code that performs a task, and that can be passed new input and return output more than once. As nouns the difference between subroutine and coroutine is that subroutine is (computer science) a section of code, called by the main body of a program, that implements a task while coroutine is (programming) a piece of code that performs a task, and that can be passed new input and return output more than once.
放上老师PPT的测试代码就收工:
def coroutine(y):
for i in range(y):
x = yield i
print("i=%d , x=%d " % (i, x))
c = coroutine(4)
next(c)
c.send(10)
c.send(20)
c.send(30)
def echo():
just_received='nothing'
try:
while True:
received=yield just_received
just_received=received
print('I got {}.'.format(just_received))
except GeneratorExit:
# when closed with close()
print('Coroutine closed!')
g = echo()
next(g)
g.send('test1')
g.send('test2')
g.close()
Reference
https://book.pythontips.com/en/latest/coroutines.html