Generator and iterator in python, python generator Generator
I personally think that iterator and yield implement the same functions, but iterator must be implemented in the class, and yield is implemented in the real function, both of which will save the status.
The generator is also implemented by the iterator.
#! /Usr/bin/env python # coding: UTF-8 # defines three functions: 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] # list of three functions # define a generator def MyGenerator (* args): for I in args: yield I a = MyGenerator (* function_list) # generator print apply (. next (), ('lil', 29) # execute the next () method. The current execution status is saved. When the next () method is called, print apply (. next ()) Print apply (a. next () # Why does yield have the next method? Looking at the column child of the iterator below, we will understand why the generator is implemented by the iterator # Below is an example of the iterator. If a class implements the _ iter _ method, the next () method is called the iterator class MyIterator (object): def _ init _ (self, funcs): self. total_funcs = len (funcs) # record the total number of functions to be executed self. func_list = funcs # record all functions self. step = 0 # record which function def _ iter _ (self): pass def next (self): if self. step <self. total_funcs: # self. step + = 1 # step return self. func_list [self. step-1] # Run the current function else: raise StopIteration c = MyIterator (function_list) print apply (c. next (), ('Lee ', 29) print apply (c. next () print apply (c. next ())