国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python UnboundLocalError和NameError錯(cuò)誤根源案例解析

2020-02-15 23:29:04
字體:
供稿:網(wǎng)友

如果代碼風(fēng)格相對(duì)而言不是那么的pythonic,或許很少碰到這類錯(cuò)誤。當(dāng)然并不是不鼓勵(lì)使用一些python語言的技巧。如果遇到這這種類型的錯(cuò)誤,說明我們對(duì)python中變量引用相關(guān)部分有不當(dāng)?shù)恼J(rèn)識(shí)和理解。而這又是對(duì)理解python相關(guān)概念比較重要的。這也是本文寫作的原因。

 本文為理解閉包相關(guān)概念的做鋪墊,后續(xù)會(huì)詳細(xì)深入的整理出閉包相關(guān)的博文,敬請(qǐng)關(guān)注。

1.案例分析

在整理閉包相關(guān)概念的過程中,經(jīng)常發(fā)現(xiàn)UnboundLocalError和NameError這兩個(gè)錯(cuò)誤,剛開始遇到的時(shí)候可能很困惑,對(duì)這樣的錯(cuò)誤無從下手。

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()

錯(cuò)誤提示:

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)

錯(cuò)誤提示:

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)

  錯(cuò)誤提示:

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

 上面的三個(gè)例子可能顯得有點(diǎn)矯揉造作,但是實(shí)際上類似錯(cuò)誤的代碼都或多或少可以在上面的例子中找到影子。這里僅僅為了說明相關(guān)概念,對(duì)例子本身的合理性不必做過多的關(guān)注。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 淅川县| 抚宁县| 上蔡县| 永嘉县| 团风县| 连城县| 托克逊县| 昌江| 兰州市| 聂荣县| 读书| 荥经县| 碌曲县| 林周县| 澄江县| 鹤峰县| 晋州市| 玛沁县| 麦盖提县| 浠水县| 长宁县| 天镇县| 武鸣县| 太谷县| 安义县| 廉江市| 苏尼特右旗| 呼图壁县| 江山市| 六安市| 集安市| 长岭县| 枣强县| 嘉峪关市| 金川县| 达尔| 佛教| 六枝特区| 麦盖提县| 五峰| 黄大仙区|