高阶函数中的闭包魔术. [英] Closure magic in higher-order functions.

查看:52
本文介绍了高阶函数中的闭包魔术.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很容易知道如何将全局变量分配给内部函数-这将使全局变量成为与内部函数相等的函数本身-但是解释器如何知道如何通过以下方式从内部函数调用自变量使用下面的代码?

It's easy to know how to assign a global variable to an inner function - which would make the global variable a function itself thats equal to the inner function - but how does the interpreter know how to call an argument from the inner function by using the code below?

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),我们看到变量/函数 a 成为内部函数.

Doing print(a), we see the variable/function a becomes the inner function.

我不明白的是,如何将 a 变量分配给外部函数,并使用代码 a('inner arguments'))将内部函数和参数作为目标对象

What I don't understand, is how assigning the a variable to the outer function targets the inner function and argument with the code, a(‘inner argument’))

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

Is it somehow implicitly calling the inner function without explicitly stating it?

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

Is it doing something like this:

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

此魔术背后的python源代码在哪里?

Where is the python source code behind this magic?

推荐答案

我没有足够的信誉来发表评论,所以我必须写一个答案...

I don't have enough reputation for a comment, so I have to write an answer...

摘自Luciano Ramalho出色的"Fluent Python":

From the excellent "Fluent Python" by Luciano Ramalho:

"... Python将本地变量和自由变量的名称保留在__code__属性,代表的已编译主体功能"

"...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"

我在您的代码中添加了两行以直观显示:

I added a couple of rows to your code to visualize this:

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__属性中.

So as you can see the value of arg is preserved even after the function has gone out of scope, since it is a free variable. The binding for arg is kept in the __closure__ attribute.

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

This is only a hint for further reading, I am by no means an expert.

这篇关于高阶函数中的闭包魔术.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆