Discuss / Python / 答题

答题

Topic source

使用nonlocal声明

def createCounter():
    n = 0
    def counter():
        nonlocal n
        n += 1
        return n
    return counter

使用list

def createCounter():
    L = [0]
    def counter():
        L[0] += 1
        return L[0]
    return counter

使用generator

def createCounter():    
    def counter():
        n = 0
        while 1:
            n += 1
            yield n
    g = counter()
    def g_fn():
        return next(g)
    return g_fn

有点问题 在使用 generator的时候

def g_fn():
        return next(g)
    return g_fn

为什么要先定义一个g_fn()函数,在里面返回next而不能像这样

g = counter()
return next(g)

直接返回next(g)呢? 会报错 'int' object is not callable

而当我改成这样

g = counter()
return g.__next__

则不会报错,运行也成功了

到底是什么原因呢?

我也没搞懂


  • 1

Reply