问题描述
我有这段代码:
#!/usr/bin/env python
def get_match():
cache=[]
def match(v):
if cache:
return cache
cache=[v]
return cache
return match
m = get_match()
m(1)
$ b b
如果我运行它,它说:
if I run it, it says:
UnboundLocalError: local variable 'cache' referenced before assignment
但如果我这样做:
#!/usr/bin/env python
def get():
y = 1
def m(v):
return y + v
return m
a=get()
a(1)
它运行。
有列表的东西吗?或者我的代码组织是错误的?
Is there something with list? or my code organizing is wrong?
推荐答案
问题是变量 c>不在函数匹配的范围内。这不是一个问题,如果你只想读它的第二个例子,但如果你分配给它,python将其解释为一个局部变量。如果你使用python 3,你可以使用
nonlocal
关键字来解决这个问题 - 对于python 2没有简单的解决方法,不幸的是。
The problem is that the variable cache
is not in the scope of the function match. This is not a problem if you only want to read it as in your second example, but if you're assigning to it, python interprets it as a local variable. If you're using python 3 you can use the nonlocal
keyword to solve this problem - for python 2 there's no simple workaround, unfortunately.
def f():
v = 0
def x():
return v #works because v is read from the outer scope
def y():
if v == 0: #fails because the variable v is assigned to below
v = 1
#for python3:
def z():
nonlocal v #tell python to search for v in the surrounding scope(s)
if v == 0:
v = 1 #works because you declared the variable as nonlocal
问题与全局变量有些相同每次分配给全局变量时,都不需要使用全局
。
The problem is somewhat the same with global variables - you need to use global
every time you assign to a global variable, but not for reading it.
的原因背后:
python解释器将所有函数编译成 function
类型的特殊对象。在此编译期间,它检查函数创建的所有局部变量(用于垃圾回收等)。这些变量名称保存在函数对象中。因为阴影一个外部范围变量(创建一个具有相同名称的变量),任何分配给并且没有显式声明为全局
的变量是完全合法的(或python3中的非本地
)假定为局部变量。
A short explanation of the reasons behind that:The python interpreter compiles all functions into a special object of type function
. During this compilation, it checks for all local variables the function creates (for garbage collection etc). These variable names are saved within the function object. As it is perfectly legal to "shadow" an outer scopes variable (create a variable with the same name), any variable that is assigned to and that is not explicitly declared as global
(or nonlocal
in python3) is assumed to be a local variable.
必须查找它遇到的每个变量引用。如果在编译期间发现变量是本地的,则在函数f_locals字典中搜索该变量。如果尚未分配,则会引发您遇到的异常。如果变量未分配给函数作用域,因此不是它的局部变量的一部分,它将在周围范围中查找 - 如果没有找到,则会引发一个类似的异常。
When the function is executed, the interpreter has to look up every variable reference it encounters. If the variable was found to be local during compilation, it is searched in the functions f_locals dictionary. If it has not been assigned to yet, this raises the exception you encountered. If the variable is not assigned to in the functions scope and thus is not part of its locals, it is looked up in the surrounding scopes - if it is not found there, this raises a similar exception.
这篇关于python闭包,在内部函数内部赋给外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!