test1 = 0
def testFunc():
test1 += 1
testFunc()
我收到以下错误:
UnboundLocalError:分配前引用的局部变量“test1”。
错误说这'test1'
是局部变量,但我认为这个变量是全局的
那么它是全局的还是局部的,如何在不将全局test1
作为参数传递给的情况下解决此错误testFunc
?
test1 = 0
def testFunc():
test1 += 1
testFunc()
我收到以下错误:
UnboundLocalError:分配前引用的局部变量“test1”。
错误说这'test1'
是局部变量,但我认为这个变量是全局的
那么它是全局的还是局部的,如何在不将全局test1
作为参数传递给的情况下解决此错误testFunc
?
为了让您test1
在函数内部进行修改,您需要将其定义test1
为全局变量,例如:
test1 = 0
def testFunc():
global test1
test1 += 1
testFunc()
但是,如果您只需要读取全局变量,则可以在不使用关键字的情况下打印它global
,如下所示:
test1 = 0
def testFunc():
print test1
testFunc()
但是每当您需要修改全局变量时,您必须使用关键字global
。
最佳解决方案:不要使用global
s
>>> test1 = 0
>>> def test_func(x):
return x + 1
>>> test1 = test_func(test1)
>>> test1
1
您必须指定 test1 是全局的:
test1 = 0
def testFunc():
global test1
test1 += 1
testFunc()