代碼如下:
myVar = 1
def myfunc():
myVar += 1
myfunc()
會(huì)提示錯(cuò)誤:
UnboundlocalError: local variable 'myVar' referenced before assignment
Python提出如下假設(shè):如果在函數(shù)體內(nèi)的任何地方對(duì)變量賦值,則Python將名稱添加到局部命名空間中。
語句myVar += 1對(duì)名稱myVar賦值,則myVar是函數(shù)myfunc的局部命名空間的一部分,而它當(dāng)前沒有關(guān)聯(lián)值,所以會(huì)產(chǎn)生錯(cuò)誤。
解決方法:使用global語句
代碼如下:
myVar = 1
def myfunc():
global myVar
myVar += 1
myfunc()
附作用域搜索規(guī)則:
L:本地的(Local)
E:封閉的(Eclosing)
G:全局的(Global)
B:內(nèi)置的(Built-in)
新聞熱點(diǎn)
疑難解答
圖片精選