python:绑定如何工作 [英] python: how binding works

查看:107
本文介绍了python:绑定如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解python中变量绑定的工作原理.我们来看一下:

I am trying to understand, how exactly variable binding in python works. Let's look at this:

def foo(x):
    def bar():
        print y
    return bar

y = 5
bar = foo(2)
bar()

这会打印出5张,这对我来说似乎很合理.

This prints 5 which seems reasonable to me.

def foo(x):
    def bar():
        print x
    return bar
x = 5
bar = foo(2)
bar()

这将打印2,这很奇怪.在第一个示例中python在执行过程中查找变量,在第二个示例中创建方法时.为什么会这样?

This prints 2, which is strange. In the first example python looks for the variable during execution, in the second when the method is created. Why is it so?

要清楚:这非常酷,并且完全按照我的意愿工作.但是,我对内部酒吧功能如何获取其上下文感到困惑.我想了解,幕后发生的事情.

To be clear: this is very cool and works exactly as I would like it to. However, I am confused about how internal bar function gets its context. I would like to understand, what happens under the hood.

编辑

我知道,局部变量具有更高的优先级.我很好奇,python在执行过程中如何知道从我先前调用的函数中获取参数.在foo中创建了bar,并且x不再存在.创建函数时是否已将此x绑定到参数值?

I know, that local variables have greater priority. I am curious, how python knows during execution to take the argument from a function I have called previously. bar was created in foo and x is not existing any more. It have bound this x to the argument value when function was created?

推荐答案

第二个示例实现了所谓的关闭.函数bar从其周围的上下文引用变量x,即函数foo.在引用全局变量x之前.

The second example implements what is called a closure. The function bar is referencing the variable x from its surrounding context, i.e. the function foo. This precedes the reference to the global variable x.

另请参阅此问题您能解释闭包吗(因为它们与Python有关)?

这篇关于python:绑定如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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