代码
1 # -*- coding:utf-8 -*-
2 import sys
3
4 def ms_fun():
5 obj = 3
6 def ms_k():
7 if obj is not 4:
8 obj = 4
9 print(obj)
10 ms_k()
11
12 if __name__ == '__main__':
13 ms_fun()
2 import sys
3
4 def ms_fun():
5 obj = 3
6 def ms_k():
7 if obj is not 4:
8 obj = 4
9 print(obj)
10 ms_k()
11
12 if __name__ == '__main__':
13 ms_fun()
上述代码会抛出 UnboundLocalError:local variable 'obj' referenced before assignment 的异常
代码
# -*- coding:utf-8 -*-
import sys
def ms_fun():
obj = 3
def ms_k():
#global obj
if obj is not 4:
global obj
obj = 4
print(obj)
ms_k()
if __name__ == '__main__':
ms_fun()
import sys
def ms_fun():
obj = 3
def ms_k():
#global obj
if obj is not 4:
global obj
obj = 4
print(obj)
ms_k()
if __name__ == '__main__':
ms_fun()
上述代码会抛出NameError: global name 'obj' is not defined
总结一下:如果你和我一样,熟悉javascript的语法,并且刚开始接触python.那么你很容易受javascript的语法 ,陷入习惯性思维误区.python的语法更灵活多变,甚至有些诡异.
如果内部函数有引用外部函数的同名变量,并且对这个变量有修改.那么python会认为它是一个局部变量.可以这样改
代码
# -*- coding:utf-8 -*-
import sys
obj = 3
def ms_fun():
def ms_k():
global obj
if obj is not 4:
obj = 4
print(obj)
ms_k()
if __name__ == '__main__':
ms_fun()
import sys
obj = 3
def ms_fun():
def ms_k():
global obj
if obj is not 4:
obj = 4
print(obj)
ms_k()
if __name__ == '__main__':
ms_fun()