高阶函数中的闭包魔法。

Closure magic in higher-order functions.

很容易知道如何将全局变量分配给内部函数——这将使全局变量本身成为一个等于内部函数的函数——但解释器如何知道如何从内部函数调用参数通过使用下面的代码功能?

def outer(arg):
    def inner(arg2):
        print(arg, ',', arg2):
    return inner

a = outer(‘outer arg’)

print(a) # .inner at 0x109bd0048
a('inner arg') # Output: outer arg, inner arg

print(a),我们看到variable/function a变成了内部函数。

我不明白的是,如何将 a 变量分配给外部函数以代码 a(‘inner argument’))

为目标的内部函数和参数

它是否以某种方式隐式调用内部函数而不显式声明它?

它是不是在做这样的事情:

a = outer('outer arg')inner('inner arg')

这个魔法背后的 python 源代码在哪里?

我没有足够的评论评论,所以我必须写一个答案...

来自 Luciano Ramalho 的优秀"Fluent Python":

"...Python keeps the names of local and free variables in the __code__ attribute that represents the compiled body of the function"

"To summarize: a closure is a function that retains the bindings of the free variables that exist when the function is defined, so that they can be used later when the function is invoked and the defining scope is no longer available"

我在您的代码中添加了几行以可视化:

def outer(arg):
    def inner(arg2):
        print(arg, ',', arg2)
    print (inner.__code__.co_freevars)
    print (inner.__closure__[0].cell_contents)
    return inner

打印以下内容:

In [169]: outer('outer arg')
('arg',)
outer arg

正如您所见,即使在函数超出范围后,arg 的值仍会保留,因为它是一个自由变量。 arg 的绑定保存在 __closure__ 属性中。

这只是进一步阅读的提示,我绝不是专家。