Source: rookie tutorial
In Python, functions that use yield are called generators.
Unlike ordinary functions, a generator is a function that returns an iterator and can only be used for iterative operations. It is easier to understand that a generator is an iterator.
In the process of calling the generator to run, the function will pause and save all current running information every time yield is encountered, return the value of yield, and continue to run from the current position when the next() method is executed next time .
Calling a generator function returns an iterator object.
The following example implements the Fibonacci sequence using yield:
import sys def fibonacci(n): #Generator function - Fibonacci a, b, counter = 0, 1 , 0 while True: if (counter > n): return yield a a, b = b, a + b counter += 1 f = fibonacci(10) # f is an iterator, returned by the generator to generate while True: try : print (next(f), end= " " ) except StopIteration: sys.exit()
Output result: 0 1 1 2 3 5 8 13 21 34 55
For the above example analysis, after the first next(f), the value of the iterator at this time is id(a)
import sys def fibonacci(n): #Generator function - Fibonacci a, b, counter = 0, 1 , 0 while True: if (counter > n): return yield a print (id(a)) print (id( a)) a, b = b, a + b counter += 1 f = fibonacci(10) # f is an iterator, returned by the generator to generate print (id(next(f))) print (next(f))
The output is as follows, found that id(next(f)) == id(a)
1424059840 1424059840 1