如果代碼風格相對而言不是那么的pythonic,或許很少碰到這類錯誤。當然并不是不鼓勵使用一些python語言的技巧。如果遇到這這種類型的錯誤,說明我們對python中變量引用相關部分有不當的認識和理解。而這又是對理解python相關概念比較重要的。這也是本文寫作的原因。
本文為理解閉包相關概念的做鋪墊,后續會詳細深入的整理出閉包相關的博文,敬請關注。
1.案例分析
在整理閉包相關概念的過程中,經常發現UnboundLocalError和NameError這兩個錯誤,剛開始遇到的時候可能很困惑,對這樣的錯誤無從下手。
1.1 案例一:
def outer_func(): loc_var = "local variable" def inner_func(): loc_var += " in inner func" return loc_var return inner_funcclo_func = outer_func()clo_func()
錯誤提示:
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
1.2 案例二:
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)
錯誤提示:
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
1.3 案例三:
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_funcclo_func = outer_func(True)print clo_func(False)
錯誤提示:
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
上面的三個例子可能顯得有點矯揉造作,但是實際上類似錯誤的代碼都或多或少可以在上面的例子中找到影子。這里僅僅為了說明相關概念,對例子本身的合理性不必做過多的關注。
新聞熱點
疑難解答