天天看點

python 子產品==命名空間?

起因: 想利用子產品傳遞某個變量,修改某個變量的值,且在其它子產品中也可見

于是我做了這樣一個實驗:

[email protected]:vearne/test_scope.git

base.py

b.py

import base
def hello():
    print 'scope base', base.value, id(base.value)
           

main.py

from base import value
from b import hello
print 'scope base', value, id(value)
value = 
print 'scope local', value, id(value)
hello()
           

運作python main.py

輸出結果如下:

['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'hello', 'value']
scope base  
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'hello', 'value']
scope local  
scope base  
           

大家可以看出,value 的值并沒有被修改,并且id值(對象的記憶體位址) 不一緻,是以我們得出結論, value 和 base.value 存在在不同位置,是兩個不同的對象。

閱讀python官方文檔

https://docs.python.org/2/tutorial/modules.html

我找到這樣一段話

Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, modname.itemname.

Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module’s global symbol table.

每個子產品有一個自己的符号表,當我們引入一個子產品時,這個符号表中的内容就會被修改,使用dir() 可以檢視目前子產品的符号表中的符号清單

看下面的列子:

print '------------------'
a = 
print dir()
print '------------------'
import math
print dir()
print '------------------'
from datetime import timedelta
print dir()
           

運作結果如下:

------------------
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'a']
------------------
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'a', 'math']
------------------
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'a', 'math', 'timedelta']
           

最後回到前面的例子:

from base import value
value =   # 這裡我們并沒有修改子產品base中value的值,而是重新定義了一個本地變量, 并且符号表中的指向已經被修改了(指向一個本地變量value)
...
           

其實這麼看python的子產品還有點像命名空間,隔離同名變量,防止命名沖突

參考資料:

https://docs.python.org/2/library/datetime.html