UnboundLocalError 与 python 中的运算符和函数式编程(方法工作正常)
prog1.py:
def runf(f):
f()
def main():
l = [0]
def f():
l.append(1)
runf(f)
print(l)
main()
给我(如预期):
[0, 1]
prog2.py:
def runf(f):
f()
def main():
l = [0]
def f():
l += [1] # <-- Only difference
runf(f)
print(l)
main()
给我:
Traceback (most recent call last):
File "prog2.py", line 11, in <module>
main()
File "prog2.py", line 8, in main
runf(f)
File "prog2.py", line 2, in runf
f()
File "prog2.py", line 7, in f
l += [1]
UnboundLocalError: local variable 'l' referenced before assignment
有人可以向我解释一下这里发生了什么吗?
注意:在 python2 和 python3 中都会发生这种情况。
另外,我愿意接受有关该问题更好标题的建议。
prog1.py:
def runf(f):
f()
def main():
l = [0]
def f():
l.append(1)
runf(f)
print(l)
main()
Gives me (as expected):
[0, 1]
prog2.py:
def runf(f):
f()
def main():
l = [0]
def f():
l += [1] # <-- Only difference
runf(f)
print(l)
main()
Gives me:
Traceback (most recent call last):
File "prog2.py", line 11, in <module>
main()
File "prog2.py", line 8, in main
runf(f)
File "prog2.py", line 2, in runf
f()
File "prog2.py", line 7, in f
l += [1]
UnboundLocalError: local variable 'l' referenced before assignment
Could someone please explain to me what's going on here?
Note: This happens in both python2 and python3.
Also, I'm open to suggestions on a better title for this question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Python 的执行模型参考(第 4.1 节)指出:
发生的情况是
l += [1]
,出于绑定的目的,相当于l = l + [1]
,这意味着l
绑定在f
内。这是另一个有趣的文档参考:otherwise 子句在这里是相关的。由于您没有在
f
范围内声明global l
并分配给l
,因此该名称绑定在的本地命名空间中f。然后,
l += [1]
隐式创建的对它的引用引用了一个尚未定义的变量。因此出现了UnboundLocalError
。顺便说一句,PS
global l
不会帮助你。 Python 3 有nonlocal
语句来处理这样的情况:The execution model reference of Python (section 4.1) states:
What happens is that
l += [1]
, for the sake of binding is equivalent tol = l + [1]
which meansl
is bound insidef
. Here's another interesting document reference:The otherwise clause is relevant here. Since you did not declare
global l
in the scope off
and assigned tol
, the name is bound in the local namespace off
. Then, the reference to it implicitly created byl += [1]
refers to a variable that hasn't been defined yet. Hence theUnboundLocalError
.P.S.
global l
wouldn't help you, by the way. Python 3 has thenonlocal
statement to handle cases like this: