1、nonlocal的作用是什么?是基於python的什么特點?
通過nonlocal關鍵字,可以使
內層的函數直接使用外層函數中定義的
變量。
在Python中,
函數的定義可以嵌套,即在一個函數的函數體中可以包含另一個函數的定義。
2、Demo
不使用nonlocal關鍵字案例
def outer(): #定義函數outer x=10 #定義局部變量x並賦為10 def inner(): #在outer函數中定義嵌套函數inner x=20 #將x賦為20 print('inner函數中的x值為:',x) inner() #在outer函數中調用inner函數 print('outer函數中的x值為:',x) outer() #調用outer函數
輸出:inner函數中的x值為: 20
outer函數中的x值為: 10
提示:在inner函數中通過第四行的“x = 20”定義了一個新的局部變量x並將其賦為20
使用nonlocal關鍵字案例
1 def outer(): #定義函數outer 2 x=10 #定義局部變量x並賦為10 3 def inner(): #在outer函數中定義嵌套函數inner 4 nonlocal x #nonlocal聲明 5 x=20 #將x賦為20 6 print('inner函數中的x值為:',x) 7 inner() #在outer函數中調用inner函數 8 print('outer函數中的x值為:',x) 9 outer() #調用outer函數
輸出:inner函數中的x值為: 20
outer函數中的x值為: 20
提示:通過“nonlocal x”聲明在inner函數中使用outer函數中定義的變量x,而不是重新定義一個局部變量x
