Yield is used to convert a function into a generator. a function with yield is no longer a common function, the Python interpreter regards it as a generator (I don't know what a generator is. I want to understand Python's generator first). a function with yield is a generator, which is different from a common function, generate a generator that looks like a function call, but does not execute any function code until next () is called for it (next () is automatically called in the for loop. Although the execution process is still executed according to the function process, every execution of a yield statement is interrupted and an iteration value is returned. the next statement of yield continues to be executed during the next execution. It seems that a function is interrupted several times by yield during normal execution, and the current iteration value is returned through yield for each interruption.
Benefits of yield:By rewriting a function as a generator, the iteration capability is obtained. compared to calculating the next () value by using the instance storage status of the class, the code is concise and the execution process is abnormal and clear.
Test code:
The code is as follows:
#! /Usr/bin/env python
#-*-Coding: utf8 -*-
Def fab (max ):
"Fibonacci data column """
N, a, B = 0, 0, 1
While n <max:
Yield B
A, B = B, a + B
N + = 1
Def perm (items, n = None ):
"Full sorting """
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