A function that contains the keyword "yield" is not a common function. When a function containing this keyword is called, the function stops running when it encounters yield and returns an iterator ). Each time you request a value, the generated code is executed. Until a yield or return occurs.
First, let's first understand what an iterator is.
LST = [1, 2, 3, 4, 5]
For I in lst
Print I
From this example, we can see that the value of I in each loop points to the next element in the list. We think this is normal. Why does I get the next element of the list?
In fact, the iterator is used in the list of for loops. Each loop iterator returns a value using the next method. Of course, this iteration is invisible to everyone.
We can implement an iterative function.
#! /Ust/bin/ENV Python
Class iterexample ():
Def _ init _ (Self ):
Self. A = 0
Def next (Self ):
Self. A + = 1
If self. A> 10: Raise stopiteration
Return self.
Def _ ITER _ (Self ):
Return self
Ie = iterexample ()
For I in IE:
Print I
By default, the above list already has an iteration method, which we do not need to implement. If a function is not iteratable, it cannot be used in a loop.
Next we will solve yield
In fact, this is very simple. However, the examples are complicated. Take a look at the following example and you will understand it immediately.
#! /Usr/bin/ENV Python
#__ Metaclass _ = Type
Def Gen ():
Print 'enter'
Yield 1
Print 'Next'
Yield 2
Print 'Next again'
For I in Gen ():
Print I
#########################
This example is printed as follows:
Enter
1
Next
2
Next again
Let me explain this program:
First, you need to know why this function can be used in the for loop. Don't ask, because this function can be iterated, that is, this function can return a value every time.
But we cannot see the _ ITER _ () and next () methods in the Gen () function. In fact, it is hidden in yield. This is how advanced languages hide a lot of things. This and C
The language is different. Every detail is displayed in the C language. Here, the program stops when it is executed to yield 1. The following program is no longer executed and a value "1" is returned ".
After the next for, the program runs down to yeild 2. If the program stops running, a value "2" is returned ". But another problem is that the "next again" under yield will be printed in the end? This may be what happens when I am in Gen () at the end of the last yield execution, resulting in the execution of the Code after the last yield.
If we modify this program as follows:
#! /Usr/bin/ENV Python
#__ Metaclass _ = Type
Def Gen ():
Print 'enter'
Yield 1
Print 'Next'
Return
Print 'Next 2'
Yield 2
Print 'Next 3'
For I in Gen ():
Print I
#######################
The program is printed as follows:
Enter
1
Next
I can see that this is the difference between yield and return. Yield can run down. After return is returned, the rest of the function cannot be executed.