python coroutine_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)

25a9b86a3ad93f12f9de1eeaeba3b37b.png

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()

cbb77b049b866b6deae1267da5fefc73.png

Reference

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值