Python has a yield expression, which can only be used to define generator functions. The generator can control the execution of functions, and the generator can suspend the execution of functions. The currently used variables and stacks will be retained, until the generator method is used next time. The following is an example of yield:
Def f (n): a, B = 1, 1; I = 0; while I
Then generate the generator object
C = f (5 );
Next, you need to call the generator method to use the generator object. The generator objects include next (), send (), throw (), close
1. next () can execute the yield statement once until the end. For example, c. next () can output 1 and call c. next () can output 2, the third call c. next () can output 3. The c generator object can execute next () up to 5 times. If it exceeds 5 times, a StopIteration exception will occur.
2. The Send () method can continue to execute the generator and pass in a value to the generator to modify the above program.
Def f (n): a, B = 1, 1; I = 0; while I
Generate a generator object, c = f (5), if you execute c. next (), c. send (5), c. send (6), the execution result is 1; 6; 11
3. The Throw () method can Throw an exception in the yield statement and cause the generator to return the value of the next generator function,
4. c. close () can generate GerneratorExit in the place where the yield generator suspends execution so that the generator exits execution. If the generator has encountered an exception before calling the close () method, close () will do nothing.
If the following generator object is generated, c = f (5) Then c. close () and then call c. the StopIteration exception occurs when you run next () because the generator Object c has exited the execution.