test1 = 0
def testFunc():
test1 += 1
testFunc()
我收到以下错误:
UnboundLocalError:在赋值之前引用了局部变量'test1‘。
错误说明'test1'
是局部变量,但我认为这个变量是全局变量
那么它是全局的还是局部的,以及如何在不将全局test1
作为参数传递给testFunc
的情况下解决此错误
发布于 2012-08-10 23:43:49
为了在函数内部修改test1
,您需要将test1
定义为全局变量,例如:
test1 = 0
def testFunc():
global test1
test1 += 1
testFunc()
但是,如果您只需要读取全局变量,则可以不使用关键字global
来打印它,如下所示:
test1 = 0
def testFunc():
print test1
testFunc()
但是,无论何时需要修改全局变量,都必须使用关键字global
。
发布于 2012-08-10 23:45:26
最佳解决方案:不使用global
>>> test1 = 0
>>> def test_func(x):
return x + 1
>>> test1 = test_func(test1)
>>> test1
1
发布于 2012-08-10 23:41:28
您必须指定test1是全局的:
test1 = 0
def testFunc():
global test1
test1 += 1
testFunc()
https://stackoverflow.com/questions/11904981
复制相似问题