Python's yield keyword

1. The function of the yield keyword

A function with yield is a generator. It is different from ordinary functions. Generating a generator looks like a function call, but will not execute any function code until next() is called (in the for loop, next() will be called automatically. )) to start execution. Although the execution flow is still executed according to the flow of the function, it will be interrupted every time a yield statement is executed, and an iteration value will be returned. The next execution will continue from the next statement of the yield. It seems as if a function is interrupted by yield several times during normal execution, and each interruption will return the current iteration value through yield.

The benefit of yield is obvious. Rewriting a function into a generator gains iterative ability. Compared with using a class instance to save the state to calculate the next next() value, not only the code is concise, but the execution flow is extremely clear.

How to judge whether a function is a special generator function? Can use isgeneratorfunction to judge.

2. Sample code

from inspect import isgeneratorfunction

def fun(max):
    b=0
    for i in range(max):
        yield b
        b+=2
    return

print('fun函数是generator(生成器)吗:',isgeneratorfunction(fun))

for i in fun(5):
    print(i)

3. Run results

fun函数是generator(生成器)吗: True
0
2
4
6
8

 

 

 

 

Guess you like

Origin blog.csdn.net/weixin_44593822/article/details/113786422