赋值前引用的局部 (?) 变量 [英] Local (?) variable referenced before assignment

查看:84
本文介绍了赋值前引用的局部 (?) 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我收到以下错误:

UnboundLocalError:在赋值之前引用了局部变量test1".

UnboundLocalError: local variable 'test1' referenced before assignment.

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

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

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

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

推荐答案

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

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 = 0
def testFunc():
    global test1 
    test1 += 1
testFunc()

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

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

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

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

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

这篇关于赋值前引用的局部 (?) 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆