賦值前引用的本地(?)變量[duplicate]

[英]Local (?) variable referenced before assignment [duplicate]


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

可能重復:賦值前引用的局部變量Python 3:UnboundLocalError:賦值前引用的局部變量

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

I am receiving the following error:

我收到以下錯誤:

UnboundLocalError: local variable 'test1' referenced before assignment.

UnboundLocalError:賦值前引用的局部變量'test1'。

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

錯誤說'test1'是局部變量,但我認為這個變量是全局的

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

那么它是全局的還是本地的,如何在不將全局test1作為參數傳遞給testFunc的情況下解決這個錯誤?

3 个解决方案

#1


133  

In order for you to modify test1 while inside a function you will need to do define test1 as a global variable, for example:

為了在函數內部修改test1,您需要將test1定義為全局變量,例如:

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

However, if you only need to read the global variable you can print it without using the keyword global, like so:

但是,如果您只需要讀取全局變量,則可以不使用關鍵字global打印它,如下所示:

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

But whenever you need to modify a global variable you must use the keyword global.

但是,無論何時需要修改全局變量,都必須使用關鍵字global。

#2


35  

Best solution: Don't use globals

最佳解決方案:不要使用全局變量

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

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

#3


7  

You have to specify that test1 is global:

您必須指定test1是全局的:

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/08/10/7259101c0aceeb3d8f672c35963e6231.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com