Yield is simply a generator. the generator is a function that remembers the position in the function body during the last return. Yield is a generator for the second (or n) Call of the generator function. the generator is a function that remembers the position in the function body during the last return. The second (or nth) call to the generator function jumps to the center of the function, while all local variables in the last call remain unchanged.
The generator is a function.
All parameters of the function are retained.
When this function is called for the second time
The parameters used are reserved for the previous time.
The generator also "remembers" it is constructed in the flow control
The generator not only "remembers" its data status. The generator also "remembers" its position in the flow control constructor (in imperative programming, this constructor is not just a data value. Because continuity allows you to jump between execution frameworks without always returning the context of the direct caller (as in the builder), it is still relatively general.
Yield generator running mechanism
When you ask the generator for a number, the generator will execute until the yield statement appears. the generator will give you the yield parameter, and then the generator will not continue to run. When you ask him to ask for the next number, he will run from the last status until the yield statement appears, give the parameter to you, and then stop. Until the function is exited.
Example: Python arrangement and combination generator
# Generate a full arrangement
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 a 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 breakprint '-'*20for b in a: print b
The result is 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 to execute, while the second loop continues with the first loop.
The above is a detailed description of yield usage in Python. For more information, see other related articles in the first PHP community!