With the keyword yield, you can generate a value from the generator and return it. We can use the generator as a producer .
In the process, by using the keyword yield, you can also let a program with yield receive values. At this point the function acts as a consumer , consuming our incoming (send) value.
In the co-process , yield can be used as the right value . In the Foo function, we write this:
n = yield
The Send method can be used to send a value to the Foo function, at which point the sent value is received by Foo and coexist in N .
The value in n can be used in the Foo function
Thus, yield is used as the right value, which makes the Foo function a consumer .
We know that the yield keyword is used to return a value to the caller.
When used as the right value, the effect of yield remains the same, and the value can still be returned to the caller.
This can be written in the Foo function as well:
n = yield C
This actually turns the Foo function into a generator that consumes the value we pass to it.
The value of n is independent of the value of C. If they have to say something, they just appear on the same line and have different interpretations of yield.
Note : The value of n is the value of our send , and the value of C is the value of the previous step of hold.
When does the value of C return ? As long as the caller uses next (), or has previously given a value to C, and now goes to yield C here, then returns.
Try to understand the following code:
defcountdown (N):Print "counting down from", N whileN >=0:newvalue= (yieldN)#If A new value got sent in, reset n with it ifNewValue is notnone:n=NewValueElse: N-= 1C= Countdown (5) forNinchC:PrintNifn = = 5: C.send (3)
Note Such a basic fact that you can tell what the output is:
For ... is to get the next value by calling the next () method, and calling the next () method, equivalent to send (None)
The output is:
Counting down from 5
5
2
1
0
start of the co-process :
C.next ()
C.send (None)
closing of the process :
C.close ()
Implementation of the co-process in Python