First, what is a generator?
A: When the function body has a yield keyword, it is called the generator.
deffoo ():Print('a') yield1Print('b') yield2Print('C') yield3x=foo ()Print(x.__next__())Print(x.__next__())
As you can see 1, the generator is an iterator
2, yield and return are the same as return value (difference?) Keep looking down)
Now that the generator is an iterator, you can use the For loop to implement this.
deffoo ():Print('a') yield1Print('b') yield2Print('C') yield3Print('D') x=foo () forIinchx:Pass
The For loop principle has been said in the iterator
Like this for loop for I in x: (#obj =x.__iter__#obj.__next__)
deffoo ():Print('a') yield1Print('b') yield2Print('C') yield3Print('D') x=foo () forIinchx:Print(i)#each time the next return value is hit.
Each next will print once, so the result of the printing is as follows: You can see that D is not a return value in the iterator will be reported stopiteration but in the for loop he will automatically capture so will not be reported abnormal
Second, the function of yield
1, the final execution of the function of the result of the iterator
2. Yield is similar to return, except that yield can return multiple values, and return can return only one value
3, follow the value of the iterator obj.__next__ (), trigger function execution, when run once obj.__next__ () The function will stop to the first yield, that is to say you write a few obj.__next__ () you function stop in the number of yield
Example:
deffoo (x):Print('Play') whileX>0:yieldx x-=1Print('Game over') G=foo (5)Print(g.__next__())Print(g.__next__())Print(g.__next__())Print(g.__next__())Print(g.__next__())Print(g.__next__())
Of course, this will be reported a stopiteration exception, the previous said that since it is an iterator can also change the code:
def foo (x): Print ('play') while x>0: yield x x-=1 print(' gameover') G-=foo (5) for in G: Print(i)
No longer write g.__next__ (), change it to a for loop to automatically catch the exception and no longer report the stopiteration exception
python--function 19, generator (i)