问题描述
我有这样的代码(简化):
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!