又名name space, 顧名思義就是存放名字的地方,存什麼名字呢?舉例說明,若變數x=1,1存放於記憶體中,那名字x存放在**呢?命名空間正是存放名字x與1繫結關係的地方
python裡面有很多名字空間,每個地方都有自己的名字空間,互不干擾,不同空間中的兩個相同名字的變數之間沒有任何聯絡。
不同變數的作用域不同就是由這個變數所在的命名空間決定的。
作用域即範圍
當程式引用某個變數的名字時,就會從當前名字空間開始搜尋。搜尋順序規則便是: legb。即locals -> enclosing function -> globals -> builtins。 一層一層的查詢,找到了之後,便停止搜尋,如果最後沒有找到,則丟擲在nameerror的異常。
level =
'l0'
n =22
deffunc()
: level =
'l1'
n =33print
(locals()
)def
outer()
: n =
44 level =
'l2'
print
("outer:"
,locals()
,n)def
inner()
: level =
'l3'
print
("inner:"
,locals()
,n)#此外列印的n是多少?
inner(
) outer(
)func(
)
輸出
outer:
44inner:
44
Python 命名空間
本文介紹python中命名空間中的legb原則。legb含 釋 l local function 函式內的名字空間,包括區域性變數和形參 e enclosing function locals 外部巢狀函式的名字空間 例如closure g global module 函式定義所在模組 檔案 的名字...
python 命名空間
作用域 第五章說過,將輸入字元作為命令放在作用域字典裡 作用域,每個函式都有乙個作用域,就是 字典,字典名字為函式名,鍵為變數,鍵值為變數對應的賦值。函式的作用域為區域性作用域 在函式內部訪問全域性變數,且只是讀取變數的值不重新繫結變數。這樣引用易出錯誤。慎重使用全域性變數 defcombine p...
python命名空間
區域性命名空間下def foo a a if name main foo 報錯資訊 unboundlocalerror local variable a referenced before assignment 全域性命名空間下if name main b b報錯資訊 nameerror name ...