1
2
3
4
5
6
7
8
9
10
11
12
13
var = 1

def fun():
var = 2
print(var)

def main():
fun()
print(var)

>>> main()
2
1

在pytho中函数中,python将var处理成同名的局部变量!

所以,当执行复合赋值运算时,会报错!

1
2
3
4
5
6
7
8
9
10
11
var = 1

def main():
var += 2
print(var)

>>> main()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in main
UnboundLocalError: local variable 'var' referenced before assignment

解决

添加global声明

1
2
3
4
5
6
7
8
9
var = 1

def main():
global var
var += 2
print(var)

>>> main()
3

参考

  1. http://stackoverflow.com/questions/10851906/python-3-unboundlocalerror-local-variable-referenced-before-assignment?lq=1
  2. python中在哪些情况下必须使用global来声明全局变量?
  3. http://stackoverflow.com/questions/8934772/assigning-to-variable-from-parent-function-local-variable-referenced-before-as

留言

2015-09-17