local variable:如果name在一个block中被绑定,该变量便是该block的一个local variable。 global variable:如果name在一个module中被绑定,该变量便称为一个global variable。 free variable: 如果一个name在一个block中被引用,但没有在该代码块中被定义,那么便称为该变量为一个free variable。
Traceback (most recent call last): File "G:\Project Files\Python Test\Main.py", line 238, in <module> clo_func() File "G:\Project Files\Python Test\Main.py", line 233, in inner_func loc_var += " in inner func" UnboundLocalError: local variable 'loc_var' referenced before assignment
经典案例2
1 2 3 4 5 6
def get_select_desc(name, flag, is_format = True): if flag: sel_res = 'Do select name = %s' % name return sel_res if is_format else name
get_select_desc('Error', False, True)
错误提示:
1 2 3 4 5 6
Traceback (most recent call last): File "G:\Project Files\Python Test\Main.py", line 247, in <module> get_select_desc('Error', False, True) File "G:\Project Files\Python Test\Main.py", line 245, in get_select_desc return sel_res if is_format else name UnboundLocalError: local variable 'sel_res' referenced before assignment
经典案例3
1 2 3 4 5 6 7 8 9 10 11
def outer_func(out_flag): if out_flag: loc_var1 = 'local variable with flag' else: loc_var2 = 'local variable without flag' def inner_func(in_flag): return loc_var1 if in_flag else loc_var2 return inner_func
clo_func = outer_func(True) print clo_func(False)
错误提示:
1 2 3 4 5 6
Traceback (most recent call last): File "G:\Project Files\Python Test\Main.py", line 260, in <module> print clo_func(False) File "G:\Project Files\Python Test\Main.py", line 256, in inner_func return loc_var1 if in_flag else loc_var2 NameError: free variable 'loc_var2' referenced before assignment in enclosing scope