问题: 通过解释器调用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 , in <module>
File "test.py", line , 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是在首行被定义,则其在解释器中被解释为全局的。
最好不要使用在首行声明定义的方式,否则容易出错