Discuss / Python / 为什么最后调用 f() 的时候 g() 会得到执行而不是返回 g() ?

为什么最后调用 f() 的时候 g() 会得到执行而不是返回 g() ?

Topic source

当年黑白

#1 Created at ... [Delete] [Delete and Lock User]
def count():
    def f(j):
        def g():
            return j*j
        return g
    fs = []
    for i in range(1,4):
        fs.append(f(i))
    return fs

为什么最后调用 f() 的时候 g() 会得到执行而不是返回 g() ?

fs.append(f(i))中f(i)是执行了的,绑定了参数i也返回了g(),但是g()函数还没执行(这里看成封装比较好理解)。可以执行count(),可以看到返回的是count().f().g()函数的地址。


  • 1

Reply