Usage analysis of Genarator function in python

  • 2020-05-07 19:56:50
  • OfStack

This article illustrates the use of Genarator functions in python. Share with you for your reference. The details are as follows:

The definition of the Generator function is no different from the definition of a normal function, except that you can use yield to generate data items in the body of the function. The Generator function can be traversed by the for loop, and the data items generated by yield 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 operation results are as follows:


0
1
2
0
1
2
Traceback (most recent call last):
 File "generator.py", line 10, in <module>
  print r.next()
StopIteration

The return value and execution principle of the yield reserved word are different from that of the return statement. The yield generated value does not abort the execution of the program, and the program continues to execute after the return value. When return returns a value, the program aborts execution.

The Generator function returns only one data item at a time, using less memory. The current state should be recorded every time the data is generated to facilitate the next generation of data.

Use the generator function when the program requires high performance or only one value at a time. Use a sequence when you need to get the value of a singleton group of elements.

As long as there is yield in the function, the function will be compiled to 1 generator function. The generator function object supports python iterator protocol. Each time the next of this object is called, the generator function executes to yield and gets the value generated by yield. If the function returns, an exception is thrown. The idea here is that the generator function USES yield to generate a value instead of returning a value. The generated function is not finished, the returned function is finished.


>>> 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()
16
>>> print x.next()
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
StopIteration
>>>

I hope this article has been helpful to your Python programming.


Related articles: