您的位置:首页 > 编程语言 > Python开发

【脚本语言系列】关于Python基础知识协程,你需要知道的事

2017-07-14 13:58 891 查看

如何使用协程(Coroutine)

协程

# -*- coding:utf-8 -*-
def fib();
a,b = 0,1
while Ture:
yield a
a,b = b,a+b
for i in fib():
print i


# -*- coding:utf-8 -*-
def grep(pattern):
print "Searching for", pattern
while True:
line = (yield)
if pattern in line:
print line

search = grep("coroutine")
next(search)
# Searching for coroutine
search.send("Here you are.")
search.send("This is coroutine.")
search.send("I get you.")
search.close()


Searching for coroutine
This is coroutine.


生成器

# -*- coding:utf-8 -*-
def fib():
a,b = 0,1
while True:
yield a
a,b = b, a+b
for i in fib():
print i


什么是协程(Coroutine)

协程用来消费数据;对应地,生成器用来产生数据;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  脚本语言 python 协程
相关文章推荐