Python 闭包 [英] Python closures
本文介绍了Python 闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
def counter(x):
def _cnt():
#nonlocal x
x = x+1
print(x)
return x
return _cnt
a = counter(0)
print(a())
上面的代码给出了以下错误
Above code gives the following error
UnboundLocalError:赋值前引用了局部变量x"
UnboundLocalError: local variable 'x' referenced before assignment
为什么这不能在_cnt的命名空间中创建一个值为'x+1'的新对象并将其绑定到x.我们将在两个函数命名空间中引用 x
Why this is not able to create a new object with value 'x+1' in the namespace of _cnt and bind it to x. we will have reference x in both function namespaces
推荐答案
一旦您分配给给定范围内的名称,同一范围内对同一名称的所有引用都是本地的.因此 x + 1
不能被评估(因为它试图引用本地 x
).
As soon as you assign to a name in a given scope, all references to the same name inside the same scope are local. Hence x + 1
cannot be evaluated (as it tries to reference the local x
).
因此这是有效的:
def f():
x = 42
def g():
print(x)
g()
f()
但这不会:
def f():
x = 42
def g():
print(x)
x = 42
g()
f()
<小时>
第一个 print
有这个字节码:
0 LOAD_GLOBAL 0 (print)
3 LOAD_DEREF 0 (x)
6 CALL_FUNCTION 1
9 POP_TOP
而第二个 print
有这个:
0 LOAD_GLOBAL 0 (print)
3 LOAD_FAST 0 (x)
6 CALL_FUNCTION 1
9 POP_TOP
这篇关于Python 闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文