函数的作用域
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 關鍵字 ,配合修改變量
30 count = 20
31 print(count)
32 inner()
33 print(count)
34 outer()
?
?
?
小結:
(1)變量查找順序:LEGB,作用域局部>外層作用域>當前模塊中的全局>python內置作用域;
(2)只有模塊/類/函數才能引入新作用域;
(3)對于一個變量,內部作用域先聲明就會覆蓋外部變量,不聲明直接使用,就會使用外部作用于的變量;
(4)內部作用域要修改外部作用域變量的值時,全局變量要使用global關鍵字,嵌套作用域變量使用nonlocal關鍵字。nonlocal時pyython3新增的關鍵字,有了這個關鍵字,就能完美的實現閉包了。
轉載于:https://www.cnblogs.com/hui147258/p/11047968.html
總結
- 上一篇: 如何转载博客
- 下一篇: svn查看登录过的账号密码