【问题标题】:Why are global variables accessible in some functions but not others?为什么在某些函数中可以访问全局变量而在其他函数中不能访问?
【发布时间】:2020-10-12 01:10:30
【问题描述】:

下面是一小段代码来说明我的问题:

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 按预期打印 indexa。但是,函数 c 既不打印这两个变量,也无法在 print 语句之后的 while 循环中访问它们。

是什么导致这两个变量在b 中可以访问,但在c 中却不能访问?

【问题讨论】:

标签: python scope global-variables


【解决方案1】:

这一行就是区别:

index += 1

如果您在函数中设置/更改一个变量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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多