nonlocal介紹
- nonlocal聲明了將要在一個(gè)嵌套的作用域中修改的名稱像啼。nonlocal應(yīng)用于一個(gè)嵌套的函數(shù)的作用域中的一個(gè)名稱潭苞,而不是所有def之外的全局模塊作用域
- 在聲明nonlocal名稱的時(shí)候,必須已經(jīng)存在于該嵌套函數(shù)的作用域中僧诚,它們只可能存在于一個(gè)嵌套的函數(shù)中振诬,并且不能由一個(gè)嵌套的def中的第一次賦值創(chuàng)建
- nonlocal 意味著定義的變量名位于一個(gè)嵌套的def中衍菱,作用域查找只限定在嵌套的def
- nonlocal只要作用是允許嵌套的作用域中的名稱被修改脊串,而不只是被引用
- nonlocal只在一個(gè)函數(shù)內(nèi)有意義
格式
def func():
nonloacal name1,name2,....
- 在默認(rèn)情況下清钥,不允許修改嵌套的def作用域中的名稱祟昭,修改嵌套作用域中的名稱會(huì)引發(fā)錯(cuò)誤
>>> def tester(start):
... state = start
... def nested(label):
... state+=1
... print(label,state)
... return nested
...
>>> F = tester('hello')
>>> F('cdef')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in nested
UnboundLocalError: local variable 'state' referenced before assignment
>>>
使用nonlocal進(jìn)行修改
將嵌套的nested中的state聲明一個(gè)nonlocal,我們就可以在nested函數(shù)中修改了
>>> def tester(start):
... state = start
... def nested(state):
... state+=1
... print(state)
... return nested
...
>>> F = tester(25)
>>> F(22)
23
邊界情況
- nonlocal語句在執(zhí)行時(shí)谜叹,nonlocal聲明的名稱必須已經(jīng)在一個(gè)嵌套的def作用域中賦值過,否則將會(huì)得到一個(gè)錯(cuò)誤:不能通過在嵌套的作用域中賦值來創(chuàng)建變量
- nonlocal限制作用域查找僅為嵌套的def,不會(huì)在嵌套的模塊的全局作用域或所有def之外的內(nèi)置作用域中查找