This example describes the use of Genarator functions in Python. Share to everyone for your reference. Specifically as follows:
The definition of a generator function is no different from the definition of a common function, except that it can be generated using yield in a function body. The generator function can be traversed by a for loop, and the yield generated data item can be obtained by the next () method.
def func (n): for
I in range (n):
yield I for
I in Func (3):
print I
r=func (3)
print r.next ()
Print R.next () print
r.next () print r.next ()
The results of the operation are as follows:
0
1
2
0
1
2
traceback (most recent call last):
File "generator.py", line, < module>
Print r.next ()
stopiteration
Yield reserved words are not the same as return values and execution principles. Yield generates a value and does not abort execution of the program, and the program continues to execute after the return value. Return returns a value, the program aborts execution.
The generator function returns only one data item at a time, consuming less memory. Each time the data is generated, the current state is logged, making it easier to generate data next time.
Use the generator function when the program requires higher performance or only one value to process at a time. Use a sequence when you need to get the value of a one-time set of elements.
This function is compiled into a generator function as long as there is a yield in the function. The Generator function object supports the Python iterator protocol. Each time the Next,generator function that calls this object executes to yield, gets the value generated by yield. If the function returns, an exception is thrown. Here's the idea that the generator function uses yield to generate a value instead of returning a value. The function is not finished after the build, and the return function ends.
>>> x = gensquares (5)
>>> print x
<generator object at 0x00b72d78>
>>> Print x.next ()
0
>>> print x.next ()
1
>>> print x.next ()
4
>>> Print X.next ()
9
>>> print x.next ()
>>> print x.next ()
traceback (most Recent call last):
File "<stdin>", line 1, in?
Stopiteration
>>>
I hope this article will help you with your Python programming.