函数的作用域
1 x=int(2.9) #int built-in
2 g_count = 0 #global
3 def outer():
4 o_count = 1 #inclosing
5 def inner():
6 i_count = 2 #local
7 print(i_count)
8 inner()
9 outer()
10
11
12 count = 10 #全局變量,在局部作用域里不能修改
13
14 def outer():
15 global count
16
17 print(count) #局部作用域不能修改全局變量的值
18 count = 5
19 print(count)
20
21 outer()
22
23
24
25
26 def outer():
27 count = 10 #局部變量
28 def inner():
29 nonlocal count #nonlocal 關(guān)鍵字 ,配合修改變量
30 count = 20
31 print(count)
32 inner()
33 print(count)
34 outer()
?
?
?
小結(jié):
(1)變量查找順序:LEGB,作用域局部>外層作用域>當(dāng)前模塊中的全局>python內(nèi)置作用域;
(2)只有模塊/類/函數(shù)才能引入新作用域;
(3)對于一個(gè)變量,內(nèi)部作用域先聲明就會(huì)覆蓋外部變量,不聲明直接使用,就會(huì)使用外部作用于的變量;
(4)內(nèi)部作用域要修改外部作用域變量的值時(shí),全局變量要使用global關(guān)鍵字,嵌套作用域變量使用nonlocal關(guān)鍵字。nonlocal時(shí)pyython3新增的關(guān)鍵字,有了這個(gè)關(guān)鍵字,就能完美的實(shí)現(xiàn)閉包了。
轉(zhuǎn)載于:https://www.cnblogs.com/hui147258/p/11047968.html
總結(jié)
- 上一篇: 如何转载博客
- 下一篇: svn查看登录过的账号密码