This article brings you an introduction to the usage of next and send in Python (code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
If send does not carry parameters, then send(None) and next() have the same effect, such as:
def a(): print('aaa') p = yield '123' #print(p) print('bbb') r = a() print(next(r)) #print(r.send(None)) #使用next(r) 和 r.send(None)输出的结果都是 #注意的是,这里的p变量的值都是None aaa
If the parameter of send is not None, the yield xx is regarded as a representation, and the value of the parameter of send is assigned to p; the subsequent operation is the same as next, such as:
def a(): print('aaa') p1 = yield '123' print('bbb') if (p1 == 'hello'): print('p1是send传过来的') p2= yield '234' print(p2) r = a() next(r) r.send('hello') #结果为 aaa bbb p1是send传过来的
Let’s talk about the order of execution. First, a() is a generator; the first execution is either next(r) or r.send(None). You cannot use r.send('xxxxx') ;This will report an error. When next(r) is executed for the first time, aaa,
is printed first, and then it jumps out when it encounters yield. Then when r.send('hello') is executed, p1 is assigned hello, and then Continue the last run, print out bbb in the next step, and then print out 'p1 is passed by send'. It will jump out when it encounters the second yield again, so the result only prints three lines, and the subsequent p2 is not executed.
The above is the detailed content of Introduction to the usage of next and send in python (code). For more information, please follow other related articles on the PHP Chinese website!