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

fox*_*eSs 108 python python-3.x

可能重复:
赋值
前引用的局部变量Python 3:UnboundLocalError:赋值前引用的局部变量

test1 = 0
def testFunc():
    test1 += 1
testFunc()
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

UnboundLocalError:赋值前引用的局部变量'test1'.

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

那么它是全局的还是本地的,如何解决这个错误而不将全局test1作为参数传递给testFunc

Flo*_*ciu 192

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

test1 = 0
def testFunc():
    global test1 
    test1 += 1
testFunc()
Run Code Online (Sandbox Code Playgroud)

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

test1 = 0
def testFunc():
     print test1 
testFunc()
Run Code Online (Sandbox Code Playgroud)

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

  • 哇,这是一个* ahem * * ahem *奇怪的语言设计决定。 (3认同)

jam*_*lak 52

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

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

>>> test1 = test_func(test1)
>>> test1
1
Run Code Online (Sandbox Code Playgroud)

  • 完全同意,你不知道全球会如何搞砸代码:) (5认同)
  • 使用编程时的良好实践概念可以更好地解决这一问题。 (2认同)

小智 9

您必须指定test1是全局的:

test1 = 0
def testFunc():
    global test1
    test1 += 1
testFunc()
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

287673 次

最近记录:

7 年,12 月 前