国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 海盐县| 丹棱县| 古丈县| 临洮县| 阜南县| 乐业县| 凤城市| 湖北省| 岫岩| 化德县| 南丰县| 梁平县| 芷江| 灵丘县| 广元市| 三穗县| 文化| 故城县| 石河子市| 邹城市| 凤庆县| 沙坪坝区| 南皮县| 布尔津县| 慈利县| 建湖县| 天台县| 改则县| 长顺县| 墨竹工卡县| 泽库县| 报价| 柳州市| 涪陵区| 余干县| 茌平县| 黄骅市| 孙吴县| 恩施市| 莎车县| 饶河县|