求问这两个函数具体是怎么运行的,且有什么不同,谢谢。
def createcounter1():
def it():
n = 1
while True:
yield n
n = n + 1
g = it()
def counter():
return next(g)
return counter
# 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
# a = createcounter1() a()=1 a()=1 a()=1
第一个函数中绑定了生成器对象g,调用next时,实际是对该对象g进行遍历,故返回结果会是1,2,3
第二个函数中未绑定对象,每次都是生成一个新的生成器,所以结果只会是1,1,1