Python靜態作用域名字搜尋規則

2021-08-25 16:53:44 字數 2664 閱讀 5483

詳細見

在程式中引用了乙個名字,python是怎樣搜尋到這個名字呢?

在程式執行時,至少存在三個命名空間可以被直接訪問的作用域:

local

首先搜尋,包含區域性名字的最內層(innermost)作用域,如函式/方法/類的內部區域性作用域;

enclosing

根據巢狀層次從內到外搜尋,包含非區域性(nonlocal)非全域性(nonglobal)名字的任意封閉函式的作用域。如兩個巢狀的函式,內層函式的作用域是區域性作用域,外層函式作用域就是內層函式的 enclosing作用域;

global

倒數第二次被搜尋,包含當前模組全域性名字的作用域;

built-in

最後被搜尋,包含內建名字的最外層作用域。

程式執行時,lgb三個作用域是一定存在的,e作用域不一定存在;

經典官方示例:

def scope_test():

def do_local():

spam = 'local spam'

def do_nonlocal():

nonlocal spam # 當外層作用域不存在spam名字時,nonlocal不能像global那樣自作主張定義乙個

spam = 'nonlocal spam' # 自由名字spam經nonlocal宣告後,可以做重繫結操作了,可寫的。

def do_global():

global spam # 即使全域性作用域中沒有名字spam的定義,這個語句也能在全域性作用域定義名字spam

spam = 'global spam' # 自有變數spam經global宣告後,可以做重繫結操作了,可寫的。

spam = 'test spam'

do_local()

print("after local assignment:", spam) # after local assignment: test spam

do_nonlocal()

print("after nonlocal assignment:", spam) # after nonlocal assignment: nonlocal spam

do_global()

print("after global assignment:", spam) # after global assignment: nonlocal spam

scope_test()

print("in global scope:", spam) # in global scope: global spam

試一試:

# coding=utf-8

def test1():

print(i)

'''test1()

nameerror: name 'i' is not defined

print()從lgb空間都沒找到自由變數i!!!

'''def test2():

print(i)

i=2'''test2()

unboundlocalerror: local variable 'i' referenced before assignment

test2()定義了區域性變數i,但是print()在i賦值前被引用!!!

'''def test3():

print(i)

i=2test3()

'''2

'''def test4():

i=1print(i)

i=2test4()

print(i)

'''1

2'''

def test5():

global i

i=1print(i)

i=2test5()

print(i)

'''1

1'''

def test6():

global i

i=3print(i)

test6()

print(i)

'''3

3'''

'''def test7():

nonlocal i #繫結到外部的i

i=3print(i)

i=1test7()

print(i)

syntaxerror: no binding for nonlocal 'i' found

'''def test8():

i=9def temp():

nonlocal i #繫結到外部的i

i=10

print(i)

temp()

print(i)

test8()

'''9

10'''

print(test8.__globals__)

''', '__builtins__': , '__file__': 'c:\\users\\li\\workspace\\temp\\e\\ttt\\try6.py', '__cached__': none, 'test1': , 'test2': , 'test3': , 'i': 3, 'test4': , 'test5': , 'test6': , 'test8': }

'''

靜態作用域

詞法作用域其實是指作用域在詞法解析階段既確定了,不會改變 基本型別 var foo 1 function sta function 列印出1 而不是 2 因為sta的scope在建立時,記錄的foo是1。如果js是動態作用域,那麼他應該彈出2 var foo 1 function sta funct...

C 網域名稱空間和作用域

網域名稱空間 通俗的講就是在乙個大括號括起來的範圍,然後用乙個名稱來稱呼。再通俗點就是告訴別人這是在哪個地盤內的事情 作用域 作用域就是宣告地盤,宣告在某個地盤,屬於哪個地盤的東西 作用域分為全域性作用域和指定區域性作用域 全域性作用域 全域性宣告的變數和函式預設作用域是全域性的,區域性的只是在乙個...

深入作用域之靜態作用域與動態作用域

概念 靜態作用域指的是一段 在它執行之前就已經確定了它的作用域,簡單來說就是在執行之前就確定了它可以應用哪些地方的作用域 變數 動態作用域在 執行的時候才確定它的作用域的,以及作用域鏈。靜態作用域 var a 10 function fn fn 11 在建立函式fn的時候就已經確定了它可以作用那些變...