gpt4 book ai didi

python - 无法在方法内访问全局变量

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:03 29 4
gpt4 key购买 nike

我有一个问题,当我尝试在方法中使用全局变量时,会产生错误(“局部变量‘b’在赋值前被引用”)。当变量是列表的元素时,为什么不是这种情况?

这很好用:

a = [1]
def a_add():
a[0] += 1

a_add()
print(a)

但这不是:

b = 1
def b_add():
b += 1

b_add()
print(b)

最佳答案

official FAQ page对此错误有详细的解释:

>>> x = 10
>>> def foo():
... print(x)
... x += 1
>>> foo()
Traceback (most recent call last):
...
UnboundLocalError: local variable 'x' referenced before assignment

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print(x) attempts to print the uninitialized local variable and an error results.

对于代码:

a = [1]
def a_add():
a[0] += 1

a_add()
print(a)

它只是从 global 数组的第一个槽中读取值并赋值,所以没有问题。

关于python - 无法在方法内访问全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43437504/

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