Yield is simply a generator, the generator is a function that remembers the position of the last time it was returned in the body of the function. A second (or nth) call to the generator function jumps to the middle of the function, and all local variables that were last called remain unchanged.
The generator is a function
All parameters of the function will be preserved
The second time this function is called
The parameters used are reserved for the previous one.
The generator also "remembers" it in flow control constructs
The generator not only "remembers" its data state. The generator also "remembers" its location in flow control constructs (in imperative programming, this construct is not just a data value). Because continuity allows you to jump arbitrarily between execution frames, rather than always returning to the context of the immediate caller (as in the case of generators), it is still more general.
The operation mechanism of yield generator
When you ask the generator to take a number, the generator executes until the yield statement appears, and the generator gives you the yield argument, and the generator does not go down. When you ask him for the next number, he will run from the last state until the yield statement appears, give you the parameters, and then stop. So repeat until you exit the function.
Example: Python permutations, Combo generators
#生成全排列
def perm (items, N=none): if n is None: n = len (items) for I in range (len (items)): v = items[i:i+1] if n = = 1: yield v else: rest = items[:i] + items[i+1:] for P in Perm (rest, n-1): yield v + P
#生成组合
def comb (items, n=none): if n is None: n = len (items) for I in range (len (items)): v = items[i:i+1] if n = = 1: yield v else: rest = items[i+1:] for C in Comb (rest, n-1): yield v + c A = perm (' abc ') for B in a: print b breakprint '-' *20for B in a: print B
The results are as follows:
102 pvopf006 ~/test>./generator.py
Abc
--------------------
Acb
Bac
Bca
Cab
Cba
As you can see, after the first loop break, the generator does not continue execution, and the second loop then executes the first loop