Detailed usage python yield (unfinished)

The yield can be seen as a return, this is intuitive, above all, a return, a normal return is to return a value in the program, and then return to the program is no longer running down. After seen then return it as a part of the generator

def foo():
    print('starting...')
    while True:
        res = yield 4
        print('res:',res)
g = foo()
print(next(g))
print("*"*20)
print(next(g))

 

Print out the results

starting...
4
********************
res:4

The above is my reasoning, this is actually printed below

starting...
4
********************
res:None
4

 

Explain run sequence code

1, after the program started, because the function foo have the yield keyword, so the function foo and not really perform, but to get a generator g (equivalent to an object)

2 until you call the next method, function foo officially started, perform print method foo function, and then enter the while loop

After 3, the program encounters the yield keyword, then the yield want to return, return a 4, the program stops and does not perform the operation assigned to the res, at this time next (g) statement is executed, the output of the first two lines ( the first is a result of the above print while the second is to return a result) is the result of performing print (next (g)) is

4, the program execution print ( "*" * 20), the output 20 *

5, they began to perform the following print (next (g)), this time above the same, the difference is, this time from the place just the next program to stop execution starts, that is to execute an assignment of res, this time to pay attention to the right this time the assignment is no value (as just that is the return out, left and did not give the assignment to pass parameters), so this time res assignment is None, so then the following output is res : None

6, the program will continue to execute while there, met again yield, this time to return the same 4, then the program stops, 4 is the return of the print function of the output of 4

Reference https://blog.csdn.net/mieleizhi0522/article/details/82142856

 

Guess you like

Origin www.cnblogs.com/z-x-y/p/12131088.html