Understanding yield in python

This question already has an answer here:

  • What does the “yield” keyword do? 36 answers

  • This is a misconception about yield . Python uses what could be called lazy evaluation. Instead of computing all "yields" in advance, it gets to the first one and stops, and then merely returns an iterator. If you were to call F(10) from the console, you would see an iterator object.

    When you start iterating over the list, eg by writing [x for x in F(10)] , then Python would execute the loop over and over and over again.

    If this is confusing, replace yield b with return b . Now the loop is not infinite any more, is it?


    The while loop does not end because the variable you are checking never changes inside it. If you were to actually decrement the num variable after each time you yield within the loop, the loop would be finite.

    Also, the loop isn't executed once the function is parsed, it is executed after line 8 invokes the function.

    Perhaps what is happening would be clearer if you tried actually iterating over the iterable produced by the function:

    for i in F(10)
        print i
    

    The result should look like this:

    1
    2
    3
    5 
    ... and so on forever
    

    I can't up-vote, but Asad is correct. Just because you define a function doesn't mean it's excited. Assuming you're running this as a script, no code is actually executed until it hits line #8.

    链接地址: http://www.djcxy.com/p/1564.html

    上一篇: 为什么这个代码产生一个发生器?

    下一篇: 了解Python中的yield