This example describes the Python builder generator usage. Share to everyone for your reference. Specifically as follows:
With yield, you can have a function generate a sequence of results, not just a value
For example:
?
1 2 3 4 5 6 7 8 9 10 11 12-13 |
def countdown (n): print "Counting Down" while N>0:yield n #生成一个n值 n-=1 >>> C = Countdown (5) >>> C.N EXT () Counting down 5 >>> c.next () 4 >>> c.next () 3 |
Next () calls the builder function until the next yield statement, at which point next () passes the return value to yield. And the function pauses execution. When you call the next time (), the function continues to execute the statement after yield. This procedure continues to execute until the function returns.
Instead of manually calling next () like the above, you use a for loop, for example:
?
1 2 3 4 5 6 7 8 9 |
>>> for I in Countdown (5): ... print I. Counting down 5 4 3 2 1 |
Next (), the return value of Send () is the argument after yield, and the difference between send () and next () is that send () is an expression that sends an argument to (yield N) as its return value to M, and next () is to send a none to (yield N) The expression, which needs to be distinguished, is the return value of the call to next (), send (), and the return value of (yield N), which is not the same. See the output can be distinguished.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16-17 |
def h (N): while n>0:m = (yield n) print "M are" +str (m) n-=1 print "N is" +str (n) >>> p= H (5) >>> P.N Ext () 5 >>> P.next () m is None-4 4 >>> p.send ("test") m is test n is 3 3 |
I hope this article will help you with your Python programming.