This article is an example of Genarator function usage in python. Shared for your reference. Specific as follows:
Generator function definition and the definition of the ordinary function is no difference, just in the function of the use of yield to generate data items can be Generator function can be traversed by the for loop, and can be obtained through the next () method yield generated data items.
def func(n): for i in range(n): yield i for i in func(3): print i r=func(3) print () print () print () print ()
The results of the run are as follows:
0 1 2 0 1 2 Traceback (most recent call last): File "", line 10, in <module> print () StopIteration
The yield reserved word is different from the return statement in terms of return value and execution principle. yield generates a value and does not abort program execution; the program continues on after the return value is returned. return returns a value and the program aborts execution.
The Generator function returns only one data item at a time, taking up less memory. Each generation of data to record the current state, so that the next generation of data.
The generator function is used when the program needs high performance or when only one value at a time needs to be processed. Use sequences when you need to get the value of a group of elements at once.
Whenever there is a yield in a function, the function is compiled into a generator function. generator function object supports the python iterator protocol. Each time next is called on this object, the generator function executes to the yield and gets the value generated by the yield. If the function returns, it throws an exception. The idea here is that the generator function uses yield to generate a value, not to return a value. Generate after the function is not over, return the function is over.
>>> x = gensquares(5) >>> print x <generator object at 0x00B72D78> >>> print () 0 >>> print () 1 >>> print () 4 >>> print () 9 >>> print () 16 >>> print () Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration >>>
I hope that what I have described in this article will help you in your Python programming.