UnboundLocalError: local variable 'a' referenced before assignment

问题: 通过解释器调用Python模块中的一个函数,该函数使用了该模块中的一个变量,调用函数后报错:

UnboundLocalError: local variable 'a' referenced before assignment

这说明Python解释器调用模块的函数的时候,该函数内部的变量作用域仅仅在函数内,想要使用函数外定义的某个变量,应当在函数内使用该变量前用 global 声明该变量为全局的。具体出问题的代码为:

test.py

# This is the first line, to ensure 'a = None' is not at the first line
a = None
def print_a():
    if a == None:
        a = "hello, this is a!"
        print(a)
    else:
        print(a)

解释器中:

>>> import test
>>> test.print_a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 4, in print_a
    if a == None:
UnboundLocalError: local variable 'a' referenced before assignment

修改方法:
test.py

# This is the first line, to ensure 'a = None' is not at the first line
a = None
def print_a():
    global a   # 声明其为module中的全局变量
    if a == None:
        a = "hello, this is a!"
        print(a)
    else:
        print(a)

解释器中:

>>> import test
>>> test.print_a()
None
>>>

补充
如果在python文件中,变量a是在首行被定义,则其在解释器中被解释为全局的。

最好不要使用在首行声明定义的方式,否则容易出错

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值