赋值前引用的局部 (?) 变量

新手上路,请多包涵
test1 = 0
def test_func():
    test1 += 1
test_func()

我收到以下错误:

UnboundLocalError:分配前引用的局部变量“test1”。

错误说 'test1' 是局部变量,但我认为这个变量是全局的

那么它是全局的还是本地的,如何在不将全局 test1 作为参数传递给 test_func 的情况下解决这个错误?

原文由 foxneSs 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 705
2 个回答

为了让您修改 test1 在函数内部,您需要将 test1 定义为全局变量,例如:

 test1 = 0
def test_func():
    global test1
    test1 += 1
test_func()

但是,如果您只需要读取全局变量,则可以在不使用关键字 global 的情况下打印它,如下所示:

 test1 = 0
def test_func():
    print(test1)
test_func()

但是,每当您需要修改全局变量时,您必须使用关键字 global

原文由 Florin Stingaciu 发布,翻译遵循 CC BY-SA 4.0 许可协议

最佳解决方案:不要使用 global s

 >>> test1 = 0
>>> def test_func(x):
        return x + 1

>>> test1 = test_func(test1)
>>> test1
1

原文由 jamylak 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题