为什么全局变量在某些函数中可以访问,而在其他函数中不能访问?
Why are global variables accessible in some functions but not others?
下面是一小段代码来说明我的问题:
index = 0
a = [1, 2, 3, 4]
def b():
print(index)
print(a)
def c():
print(index)
print(a)
while a[index] < 3:
index += 1
b()
c()
我得到以下输出:
0
[1, 2, 3, 4]
Traceback (most recent call last):
File "global.py", line 14, in <module>
c()
File "global.py", line 8, in c
print(index)
UnboundLocalError: local variable 'index' referenced before assignment
函数 b
按预期打印了 index
和 a
。但是,函数 c
既不打印这两个变量,也似乎无法在打印语句后的 while
循环中访问它们。
是什么导致这两个变量在 b
中可访问但在 c
中不可访问?
这一行的区别是:
index += 1
如果您 set/change 在函数中 anywhere 变量,Python 假定它是局部变量而不是一个全局的,无处不在的函数。这就是你的两个功能之间的区别,b()
不会尝试更改它。
要解决此问题,您只需输出:
global index
在 c()
函数的顶部,它告诉它无论如何都假设为全局。您可能也想在 b()
中这样做,只是为了明确和一致。
或者,您可以找到一种方法 不使用 全局变量,这可能更可取 :-) 类似于:
index = 0
a = [1, 2, 3, 4]
def b(idx, arr):
print(idx)
print(arr)
def c(idx, arr):
print(idx)
print(arr)
while arr[idx] < 3:
idx += 1
return idx
b(index, a)
index = c(index, a)
下面是一小段代码来说明我的问题:
index = 0
a = [1, 2, 3, 4]
def b():
print(index)
print(a)
def c():
print(index)
print(a)
while a[index] < 3:
index += 1
b()
c()
我得到以下输出:
0
[1, 2, 3, 4]
Traceback (most recent call last):
File "global.py", line 14, in <module>
c()
File "global.py", line 8, in c
print(index)
UnboundLocalError: local variable 'index' referenced before assignment
函数 b
按预期打印了 index
和 a
。但是,函数 c
既不打印这两个变量,也似乎无法在打印语句后的 while
循环中访问它们。
是什么导致这两个变量在 b
中可访问但在 c
中不可访问?
这一行的区别是:
index += 1
如果您 set/change 在函数中 anywhere 变量,Python 假定它是局部变量而不是一个全局的,无处不在的函数。这就是你的两个功能之间的区别,b()
不会尝试更改它。
要解决此问题,您只需输出:
global index
在 c()
函数的顶部,它告诉它无论如何都假设为全局。您可能也想在 b()
中这样做,只是为了明确和一致。
或者,您可以找到一种方法 不使用 全局变量,这可能更可取 :-) 类似于:
index = 0
a = [1, 2, 3, 4]
def b(idx, arr):
print(idx)
print(arr)
def c(idx, arr):
print(idx)
print(arr)
while arr[idx] < 3:
idx += 1
return idx
b(index, a)
index = c(index, a)