【脚本语言系列】关于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基础知识文件操作,你需要知道的事
- 【脚本语言系列】关于Python基础知识设计模式,你需要知道的事
- 【脚本语言系列】关于Python基础知识枚举,你需要知道的事
- 【脚本语言系列】关于Python基础知识容器,你需要知道的事
- 【脚本语言系列】关于Python基础知识装饰器,你需要知道的事
- 【脚本语言系列】关于Python基础知识多返回值,你需要知道的事
- 【脚本语言系列】关于Python基础知识__slots__,你需要知道的事
- 【脚本语言系列】关于Python基础知识映射器和过滤器,你需要知道的事
- 【脚本语言系列】关于Python基础知识异常处理,你需要知道的事
- 【脚本语言系列】关于Python基础知识调试,你需要知道的事
- 【脚本语言系列】关于Python基础知识函数缓存,你需要知道的事
- 【脚本语言系列】关于Python基础知识推导式,你需要知道的事
- 【脚本语言系列】关于Python基础知识迭代器,你需要知道的事
- 【脚本语言系列】关于Python基础知识处理字符串,你需要知道的事
- 【脚本语言系列】关于Python基础知识面向对象编程,你需要知道的事
- 【脚本语言系列】关于Python基础知识兼容Python 2.x+Python 3.x,你需要知道的事
- 【脚本语言系列】关于Python基础知识魔法变量,你需要知道的事
- 【脚本语言系列】关于Python基础知识对象自省,你需要知道的事
- 【脚本语言系列】关于Python基础知识Lambda表达式,你需要知道的事
- 【脚本语言系列】关于Python基础知识对象变动,你知道的事