[英]How do I change global variable in nested scope using python?
My example below.我的例子如下。 I have tried adding
global
to the variable that I want to change but doesn't help.我曾尝试将
global
添加到我想要更改的变量中,但没有帮助。 The error I'm getting is in the comment.我得到的错误在评论中。
def getNumOfSwapsToSort(array):
sorted = array.copy()
sorted.sort()
swaps = 0
def swap():
currentSwaps = 0
for i, el in enumerate(array):
if ((len(array) - 1) == i) and currentSwaps != 0:
swap()
elif el != sorted[i]:
idx = sorted.index(el)
temp = array[idx]
array[idx] = el
array[i] = temp
# UnboundLocalError: local variable 'swaps' referenced before assignment
# if I use global swaps, then NameError: name 'swaps' is not defined
swaps += 1
currentSwaps += 1
swap()
return swaps
The swaps
variable in your code is not global, it's nonlocal .代码中的
swaps
变量不是全局变量,而是nonlocal 。 It was defined in the enclosing function getNumOfSwapsToSort()
, not in the global namespace.它是在封闭函数
getNumOfSwapsToSort()
定义的,而不是在全局命名空间中。
Your other function, swap()
, has access to this nonlocal variable, but the variable is protected from being edited from the inner function.您的另一个函数
swap()
可以访问此非局部变量,但该变量受到保护,不会被内部函数编辑。 If you try to edit or overwrite it, it's going to be treated as a new, local variable - hence the UnboundLocalError you're getting.如果您尝试编辑或覆盖它,它将被视为一个新的局部变量 - 因此您会得到 UnboundLocalError。
Try using the nonlocal
statement :尝试使用
nonlocal
语句:
nonlocal swaps
swaps += 1
Here's an article with a few simple examples which explain the concept of closure in Python .这是一篇带有一些简单示例的文章,它们解释了Python 中闭包的概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.