带有嵌套函数作用域的 UnboundLocalError [英] UnboundLocalError with nested function scopes
问题描述
我有这样的代码(简化):
I have code like this (simplified):
def outer():
ctr = 0
def inner():
ctr += 1
inner()
但是 ctr
导致错误:
Traceback (most recent call last):
File "foo.py", line 9, in <module>
outer()
File "foo.py", line 7, in outer
inner()
File "foo.py", line 5, in inner
ctr += 1
UnboundLocalError: local variable 'ctr' referenced before assignment
我该如何解决这个问题?我认为嵌套范围可以让我这样做.我试过全局",但它仍然不起作用.
How can I fix this? I thought nested scopes would have allowed me to do this. I've tried with 'global', but it still doesn't work.
推荐答案
如果您使用的是 Python 3,则可以使用 nonlocal
语句启用重新绑定非本地名称:
If you're using Python 3, you can use the nonlocal
statement to enable rebinding of a nonlocal name:
def outer():
ctr = 0
def inner():
nonlocal ctr
ctr += 1
inner()
如果您使用的 Python 2 没有 nonlocal
,则需要在不重新绑定裸名的情况下执行递增(通过将计数器保留为某个裸名的项目或属性, 不 作为一个裸名本身).例如:
If you're using Python 2, which doesn't have nonlocal
, you need to perform your incrementing without barename rebinding (by keeping the counter as an item or attribute of some barename, not as a barename itself). For example:
...
ctr = [0]
def inner():
ctr[0] += 1
...
当然,现在在其他地方使用裸 ctr
的任何地方都使用 ctr[0]
.
and of course use ctr[0]
wherever you're using bare ctr
now elsewhere.
这篇关于带有嵌套函数作用域的 UnboundLocalError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!