A function with yield is a generator, which, unlike a normal function, generates a generator that looks like a function call, but does not execute any function code until it calls next () (which is automatically called next () in the For loop) to begin execution. Although the execution process still executes according to the process of the function, each execution to a yield statement is interrupted and an iteration value is returned, and the next execution proceeds from the next statement of yield. It looks as if a function was interrupted several times by yield during normal execution, and each break returns the current iteration value through yield.
yield Benefits: by rewriting a function as a generator, we get the iterative ability to calculate the value of the next next () rather than the instance holding state of the class, not only the code is concise, but the execution process is exceptionally clear.
Test code:
Copy the Code code as follows:
#!/usr/bin/env python
#-*-Coding:utf8-*-
Def FAB (max):
"" "Fibonacci Numbers" ""
N, a, b = 0, 0, 1
While n < max:
Yield b
A, B = B, A + b
n + = 1
def perm (items, N=none):
"" "Full Arrangement" ""
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
if __name__ = = ' __main__ ':
For N in Fab (5):
Print n
Print "Full arrangement: 123"
For N in Perm ("123"):
Print n