python學習第十天,名稱空間與範圍,函數的嵌套,global 和 nonlocal

來源:互聯網
上載者:User

標籤:時空   全域   print   定義   pass   class   test   inner   global   

名稱空間:

  內建名稱空間: 在開啟pytharm是載入

  全域名稱空間: 在運行py檔案是載入

  局部名稱空間(臨時名稱空間) :在py檔案中調用時載入

def func(): ----->函數定義

  pass ------->函數體

func()------------->函數調用

  

函數定義時:記憶體中只儲存與函數名的對應關係,函數體的內容不儲存

函數調用時:才執行函數體的內容,建立臨時空間,隨著函數執行結束,記憶體中的臨時名稱空間裡面的內容也清空 

 

範圍:

  全域範圍:內建名稱空間裡的內容+全域名稱空間裡的內容

  局部範圍:局部名稱空間

取值順序:

  局部--->全域--->內建 ,單向取值,無法復原.

a=10b=20def test5(a,b):    print(a,b) ---> 20,10    a=3    b=5    print(a,b) ---> 3,5c = test5(b,a)print(c) ---------> None

 

載入順序:

  內建名稱空間

  全域名稱空間

  局部名稱空間

函數的嵌套:

  看到調用就執行

global 和 nonlocal(當資料類型是不可變的時候需要申明,但是當資料類型是列表的時候,可以直接用append往列表添加資料,同時直接引起全域變數的改變)

  global:申明函數內的元素可以作為全域變數 (函數可以直接引用全域變數,沒有global不能改變全域變數)

  nonlocal:申明子級函數可以改變父級函數的變數 ,但nonlocal不能改變全域變數(子級函數可以直接引用父級函數的變數,沒有nonlocal不能改變父級函數的變數)

count = 1def func1():    count += 1 # 會報錯 # count = 2 不會報錯    print(count)func1() 
def func1():    count = 666    def inner():        print(count)        def func2():            nonlocal count            # global count            count += 1            print(‘func2‘,count)        func2()        print(‘inner‘,count)    inner()    print(‘func1‘,count)func1()print(count)

python學習第十天,名稱空間與範圍,函數的嵌套,global 和 nonlocal

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.