Discuss / Python / 作业_返回函数

作业_返回函数

Topic source

落之萧萧

#1 Created at ... [Delete] [Delete and Lock User]

def createCounter(): def b(): n = 0 while True: n += 1 yield n i = b() def counter(): return next(i) return counter

我思路和你一样:

def createCounter(): def natural_int(): i = 1 while True: yield i i+=1

#it = natural_int()
def counter():
    return next(natural_int())
return counter

可是这样就错了,为啥,全是1

个人理解: return next(natural_int())这里natural_int()只是临时的generator,调用后就会销毁。return next(i)的话i已经在counter()外部定义了,可以一直使用。

M_______7

#4 Created at ... [Delete] [Delete and Lock User]

原理不懂, 但生成器那章 有这样一句话 “调用该generator时,首先要生成一个generator对象,然后用next()函数不断获得下一个返回值”

每次调用CreatCounter都会生成一个新的natural_int函数,都是1也就好理解了。最上面的是把生成器赋值给了i,然后再调用i,你的代码是直接调用生成器函数。


  • 1

Reply