How does a function in Python remember its values after it returns?

This question already has an answer here:

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

  • A simplified answer.

    If you have a function that generates a sequence of values, you may transform it in a generator by using yield.

    def func():
        for i in range(3):
            yield i
    
    list(func()) ==> [0,1,2]
    
    for el in func():
        print(el) # 0
                  # 1
                  # 2
    

    Each time yield is called the function is frozen somewhere. When it is called again it continues from his last state, and doesn't start anew (unless it has finished to consume elements).

    If you call the function you get a generator , which is something you can iterate over.

    Note that this way you may iterate over infinite sequences without the need to use infinite memory.

    def inf():
        x = -1
        while True:
            x = x + 1
            yield x
    
    for i in inf():
        if i < 10:
            print(i)
        else:
            break
    

    This is because those functions aren't functions, but generators. The yield statement returns a value, but doesn't return from the function. Each time you call next on the generator, it continues the execution of the generator from the last call, until it reaches yield statement again.


    In principle your first assumption was right: the variables of a function are only available while the function is executed. In your case however, you are using the yield statement. As a result the function call returns an iterator, which, when called, returns the value of the next yield statement.

    Check this post for further explanations on what iterators are and do.

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

    上一篇: 无法理解python生成器

    下一篇: Python中的函数在返回后如何记住它的值?