日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

函数的作用域

發布時間:2024/9/5 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 函数的作用域 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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

總結

以上是生活随笔為你收集整理的函数的作用域的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。