Local (?) variable referenced before assignment

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

I am receiving the following error:

UnboundLocalError: local variable 'test1' referenced before assignment.

Error says that 'test1' is local variable but i thought that this variable is global

So is it global or local and how to solve this error without passing global test1 as argument to test_func?

465496 次浏览

您必须指定 test1是全局的:

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

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

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

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

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

但是,无论何时需要修改全局变量,都必须使用关键字 global

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

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


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