python 模組==命名空間?

來源:互聯網
上載者:User

標籤:python   scope   dir   

起因: 想利用模組傳遞某個變數,修改某個變數的值,且在其它模組中也可見
於是我做了這樣一個實驗:
[email protected]:vearne/test_scope.git

base.py

value = 10

b.py

import basedef hello():    print ‘scope base‘, base.value, id(base.value)

main.py

from base import valuefrom b import helloprint ‘scope base‘, value, id(value)value = 20print ‘scope local‘, value, id(value)hello()

運行python main.py
輸出結果如下:

[‘__builtins__‘, ‘__doc__‘, ‘__file__‘, ‘__name__‘, ‘__package__‘, ‘hello‘, ‘value‘]scope base 10 140195531889072[‘__builtins__‘, ‘__doc__‘, ‘__file__‘, ‘__name__‘, ‘__package__‘, ‘hello‘, ‘value‘]scope local 20 140195531888832scope base 10 140195531889072

大家可以看出,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 = 15print dir()print ‘------------------‘import mathprint dir()print ‘------------------‘from datetime import timedeltaprint 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 valuevalue = 20  # 這裡我們並沒有修改模組base中value的值,而是重新定義了一個本地變數, 並且符號表中的指向已經被修改了(指向一個本地變數value)...

其實這麼看python的模組還有點像命名空間,隔離同名變數,防止命名衝突

參考資料:
https://docs.python.org/2/library/datetime.html

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

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.