Python - 如何从函数中引用全局变量

标签 python scope

<分区>

我一定是遗漏了一些关于 Python 变量范围的非常基本的概念,但我不知道是什么。

我正在编写一个简单的脚本,我想在其中访问在函数范围之外声明的变量:

counter = 0

def howManyTimesAmICalled():
    counter += 1
    print(counter)

howManyTimesAmICalled()

出乎我意料的是,在运行时我得到:

UnboundLocalError: local variable 'counter' referenced before assignment

在第一行添加全局声明

global counter
def howManyTimesAmICalled():
    counter += 1
    print(counter)

howManyTimesAmICalled() 

没有更改错误信息。

我做错了什么?正确的做法是什么?

谢谢!

最佳答案

您需要在函数定义中添加global counter。 (不在你的代码的第一行)

你的代码应该是

counter = 0

def howManyTimesAmICalled():
    global counter
    counter += 1
    print(counter)

howManyTimesAmICalled()

关于Python - 如何从函数中引用全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17928791/

相关文章:

python - 在 doctests 中修改全局变量

python - 为什么 Python 中的函数可以在封闭范围内打印变量但不能在赋值中使用它们?

c++ - 使用 "new"的类作用域

python - 在 matplotlib 图中使用 Pandas 数据帧索引作为 x 轴的值

python - 预期的 LP_c_float 实例而不是 glVertex3fv 中的元组

c - 下次运行时需要将变量存储在哪里?

javascript - 从不同范围访问 "this"

c++ - 为什么这运行良好? (访问范围外变量的地址)

python - 我可以在记录时设置为 gevent greenlet 显示的自定义名称吗?

python - 如何在带有附加图表的 matplotlib 表中使用逗号分隔符格式化值?