本地(?)赋值前引用的变量

2024-04-25 09:03:54 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
local var referenced before assignment
Python 3: UnboundLocalError: local variable referenced before assignment

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

我收到以下错误:

UnboundLocalError: local variable 'test1' referenced before assignment.

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

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


Tags: varlocaldef错误error全局variabletest1
3条回答

必须指定test1是全局的:

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

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

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

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

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

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

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

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

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

相关问题 更多 >