153
test1 = 0
def testFunc():
    test1 += 1
testFunc()

我收到以下错误:

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

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

那么它是全局的还是局部的,如何在不将全局test1作为参数传递给的情况下解决此错误testFunc

4

3 回答 3

262

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

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

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

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

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

于 2012-08-10T15:43:48.800 回答
59

最佳解决方案:不要使用globals

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

>>> test1 = test_func(test1)
>>> test1
1
于 2012-08-10T15:45:26.357 回答
11

您必须指定 test1 是全局的:

test1 = 0
def testFunc():
    global test1
    test1 += 1
testFunc()
于 2012-08-10T15:41:28.007 回答