0

考虑以下示例:

def g():

    in_g=100

    def f1():
        nonlocal in_g
        in_g = 10

    def f2():
        nonlocal in_g
        print(in_g)

    return (f1,f2)


(f1, f2) = g()

f2() #prints 100
f1()
f2() #prints 10

内部函数f1f2都在其“闭包”中访问变量in_g。但是,g返回后,在in_g内存中保存在哪里?

我假设在g执行时,in_g是堆栈帧上的一个变量,对应于对g. 因此,gf1f2在使用变量时访问相同的内存位置(在堆栈上)in_g

但是,如示例中所见,在g返回之后f1f2在引用in_g. 但是,现在g返回了,该内存位置不能再在堆栈上。

4

2 回答 2

0

上述代码的输出是 100 & 10 。


因为第一个 f2() 调用,所以它直接访问 in_g 变量并打印它的值。在 f1() 调用之后,它将 in_g 变量值更新为 10。然后 f2() 函数再次调用,因此由于 nonlocal 语句它绑定以前的值这就是它打印 10 值的原因。


The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope. Names listed in a nonlocal statement, unlike those listed in a global statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously). Names listed in a nonlocal statement must not collide with pre-existing bindings in the local scope.


于 2018-01-14T09:16:04.183 回答
0

I believe I found the answer here: http://stupidpythonideas.blogspot.ro/2015/12/how-lookup-works.html.

So, when accessing in_g, g, f1 and f2 access a cell variable which, in turn, holds a reference to the actual object.

于 2018-01-14T10:45:10.083 回答