fox*_*eSs 108 python python-3.x
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.
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)
小智 9
您必须指定test1是全局的:
test1 = 0
def testFunc():
global test1
test1 += 1
testFunc()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
287673 次 |
| 最近记录: |