python函數名稱空間

來源:互聯網
上載者:User

標籤:tin   UI   ...   color   結果   pytho   傳回值   family   font   

一、命名空間概念

命名空間(name space),若變數x=1,1存放在記憶體中,命名空間是存放名字x、x與1綁定關係的地方。
命名空間分三種:

  • locals:函數內的名稱空間,包括局部變數和形參
  • globals:全域變數,函數定義所在模組的名字空間
  • builtins:內建模組的名字空間 dir(__builtins__)查看所有內建方法

範圍:python中一個函數就是一個範圍,局部變數放置在其範圍中;代碼定義完成後,範圍已經完成,範圍鏈向上尋找
    C# Java中範圍{}

不同變數的範圍不同就是由這個變數所在的命名空間決定的:
範圍即範圍:
  全域範圍:全域存活,全域有效
  局部範圍:臨時存活,局部有效

二、範圍尋找順序

 

LEGB:locals ——>enclosing(相鄰的上一級) ——>globals ——> __builtins__
  • locals 是函數內的名字空間,包括局部變數和形參
  • enclosing 外部嵌套函數的名字空間
  • globals 全域變數,函數定義所在模組的名字空間
  • builtins 內建模組的名字空間
n = 10def fun1():    n = 20    print(‘func1‘,n)    def fun2():        n = 30        print(‘func2‘,n)        def func3():            print("func3",n)    # locals沒有,先找相鄰上一級範圍        func3()  # 20    fun2()  # 30  fun1()  # 30
def func():    level = ‘L1‘    n = 33    print(locals())  # {‘level‘: ‘L1‘, ‘n‘: 33}    def outer():        n = 44        level = ‘L2‘        print(locals(), n)        def inner():            level = ‘L3‘            print(locals(), n)        inner()  # {‘n‘: 44, ‘level‘: ‘L3‘} 44    outer()  # {‘n‘: 44, ‘level‘: ‘L2‘} 44func()
三、嵌套函數傳回值
age = 18def func1():    age = 73    def func2():        age = 84        print(age)    return 666val = func1()print(val)‘‘‘輸出:666‘‘‘# 函數名可以當作傳回值age = 18def func1():    age = 73    def func2():...    return func2   # 返回一個函數名# val = func1()print(val)‘‘‘輸出:<function func1.<locals>.func2 at 0x101462598>‘‘‘# 代碼寫完之後範圍已經產生,不管函數名傳到哪裡,只要執行都回回定義的地方往上找age = 18def func1():    age = 73    def func2():        print(age)    return func2   # 返回一個函數名不帶括弧val = func1()val()‘‘‘輸出結果:73‘‘‘
四、查看範圍方法

globals(),locals()

 

python函數名稱空間

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.