On the problem of return function

ask exactly how the two functions work and what"s the difference. Thank you.

clipboard.png

def createcounter1():
    def it():
        n = 1
        while True:
            yield n
            n = n + 1
    g = it()   

    
    def counter():
        return next(g)
    return counter

-sharp a = createcounter1()  a()=1 a()=2  a()=3 


def createcounter2():
    def it():
        n = 1
        while True:
            yield n
            n = n + 1
    def counter():
        return next(it())   

    return counter

-sharp a = createcounter1()  a()=1 a()=1  a()=1

Jun.24,2021

the generator object g is bound in the first function, and when next is called, the object g is actually traversed, so the returned result will be the unbound object in the second function, and a new generator will be generated each time, so the result will only be 1LJ 1

.
Menu