yield is simply a generator. A generator is a function that remembers the position in the function body when it last returned. The second (or nth) call to a generator function jumps to the middle of the function, leaving all local variables unchanged from the previous call.
The generator is a function
All parameters of the function will be retained
When this function is called for the second time
The parameters used are retained from the previous time.
The generator also "remembers" it in the flow control Constructing a
generator doesn’t just “remember” its data state. The generator also "remembers" its position within the flow control construct (in imperative programming, this construct is not just a data value). Continuity is still relatively general since it lets you jump arbitrarily between execution frames without always returning to the immediate caller's context (as with generators).
The operating mechanism of the yield generator
When you ask the generator for a number, the generator will execute until the yield statement appears. The generator will give you the parameters of yield, and then the generator will not continue to run. When you ask him for the next number, he will start running from the last state until the yield statement appears, give you the parameters, and then stop. Repeat this until the function exits.
Example: Python permutation, combination generator
#Generate full permutation
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
#Generate combination
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 break print '-'*20 for 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 is executed, and the second loop is executed after the first loop