Generator function: If the yield keyword appears in the function, then this function is the generator function, and yield is the function of generating a generator, and the generator function returns a generator.
A generator is created by implementing a generator:1, replacing the list's [] with ().
>>> L = [x * x for x in range(10)]>>> L[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]>>> g = (x * x for x in range(10))>>> g<generator object <genexpr> at 0x1022ef630>
Mode 2, through the yield keyword. If a function definition contains a yield
keyword, then the function is no longer a normal function, but a generator.
The generator implements the __iter__ method and the next () method. The generator is an iterative object and an iterator. Can be used for a for loop.
There is a lot of overhead in building iterators in Python; You must use the __iter__()
and __next__()
method to implement a class that tracks the internal state and throws an exception when no value is returned StopIteration
.
The Python builder is an easy way to create iterators.
1. Call the generator function and return a generator.
2. When invoking the next () method of the generator, the generator starts executing the generator function until it encounters yield and pauses execution (hangs), and the yield parameter is used as the return value of the next method.
3. After each call to the next method of the generator, the generator resumes execution of the generator function from the location where it was last paused until the yield is encountered again, and the yield parameter will be the return value of the next method.
Python Learning-Generator generator