Personally feel that iterator and yield achieve the same function, but iterator need to implement in the class, yield is implemented in the real function, both will save the state
The generator is also implemented by iterators
#!/usr/bin/env python#coding:utf-8# definition three functions def Lee (name,age): Return ' I am%s,i am%d old '% (name,age) def Ma Rlon (): Return ' I am Marlon ' Def Allen (): Return ' I am Allen ' function_list= [Lee,marlon,allen] #有三个函数的列表 # definition A generator def mygenerator (*args): For i in Args:yield I a=mygenerator (*function_list) #生成器print apply (A.next (' Lee ',)) #执行next () method, which saves the current execution state, and the next time the next () method is called, print apply (A.next ()) print apply (A.next ()) # Why does yield have next method? Look at the iterator below to see why the generator is implemented by the iterator # below is an example of an iterator, a class that implements the __iter__ method, and the next () method, which is called an iterator class Myiterator (object): Def __init__ (Self,funcs): Self.total_funcs=len (funcs) #记录总共需要执行多少个函数 self.func_list=funcs #记录所有函数 self.step = 0 #记 Record which function is currently executed Def __iter__ (self): Pass def Next: If Self.step < self.total_funcs: #当目前所 The function being executed is less than the total number of functions Self.step+=1 #step return self.func_list[self.step-1] #执行当前函数 else: Raise Stopiteration C=myiterator (function_list) print apply (C.next (), (' Lee ', +)) print apply (C.next ()) print apply (C.next ())
Generators and iterators in Python