首页 / 操作系统 / Linux / Python中的生成器和迭代器
个人觉得iterator和yield实现的是相同的功能,只不过iterator需要在类中实现,yield实在函数中实现,二者均会保存状态生成器也是由迭代器实现的#!/usr/bin/env python #coding: utf-8 #定义三个函数 def Lee(name,age): return "I am %s,I am %d old" %(name,age) def Marlon(): return "I am Marlon" def Allen(): return "I am Allen" function_list= [Lee,Marlon,Allen] #有三个函数的列表#定义一个生成器 def MyGenerator(*args): for i in args: yield i a=MyGenerator(*function_list) #生成器 print apply(a.next(),("Lee",29)) #执行next()方法,这时会保存现在的执行状态,下一次调用next()方法时,会用到此状态 print apply(a.next()) print apply(a.next())#为什么yield有next方法? 看下面迭代器的列子,就会明白为什么生成器是由迭代器实现的 #下面是迭代器的例子, 一个类如果实现了__iter__方法,和next()方法,就叫做迭代器 class MyIterator(object): def __init__(self,funcs): self.total_funcs=len(funcs)#记录总共需要执行多少个函数 self.func_list=funcs #记录所有函数 self.step = 0 #记录当前执行到哪一个函数 def __iter__(self): pass def next(self): if self.step < self.total_funcs: #当目前所执行的函数所在的位置小于总的函数个数时 self.step+=1 #step return self.func_list[self.step-1] #执行当前函数 else: raise StopIteration c=MyIterator(function_list) print apply(c.next(),("Lee",29)) print apply(c.next()) print apply(c.next())--------------------------------------分割线 --------------------------------------CentOS上源码安装Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htm Python脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htmPython 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htmPython 的详细介绍 :请点这里Python 的下载地址 :请点这里本文永久更新链接地址 :http://www.linuxidc.com/Linux/2015-02/113561.htm
收藏该网址