gpt4 book ai didi

python - 如何使用 python 更改嵌套作用域中的全局变量?

转载 作者:行者123 更新时间:2023-11-30 21:50:49 24 4
gpt4 key购买 nike

我的例子如下。我尝试将 global 添加到我想要更改的变量中,但没有帮助。我收到的错误在评论中。

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

最佳答案

代码中的 swaps 变量不是全局变量,而是非本地。它是在封闭函数 getNumOfSwapsToSort() 中定义的,而不是在全局命名空间中。

您的另一个函数 swap() 可以访问此非局部变量,但该变量受到保护,无法从内部函数进行编辑。如果您尝试编辑或覆盖它,它将被视为新的局部变量 - 因此您会得到 UnboundLocalError 。

尝试使用nonlocal statement :

nonlocal swaps
swaps += 1

这里有一篇文章,其中包含一些简单的示例,解释了 concept of closure in Python .

关于python - 如何使用 python 更改嵌套作用域中的全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60267960/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com