2009-08-19 53 views
6
"""module a.py""" 
test = "I am test" 
_test = "I am _test" 
__test = "I am __test" 

=============爲什麼「導入」與「導入*」有區別?

~ $ python 
Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) 
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> from a import * 
>>> test 
'I am test' 
>>> _test 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name '_test' is not defined 
>>> __test 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name '__test' is not defined 
>>> import a 
>>> a.test 
'I am test' 
>>> a._test 
'I am _test' 
>>> a.__test 
'I am __test' 
>>> 

回答

21

變量與一家領先的 「_」(下劃線)不公開姓名並不會導入當使用from x import *

這裏,_test__test不是公共名稱。

import語句描述的:

如果標識符列表用星號(「*」),該模塊中定義的所有公共名 都註定的了 本地命名空間代替 進口 聲明..

由模塊 定義的公共名稱是由檢查 模塊的命名空間的變量 名爲__all__確定;如果被定義,它必須是 這個字符串序列,其名稱爲 ,由該模塊定義或導入。 在__all__中給出的名稱全部爲 ,視爲公共並且需要存在 。 如果__all__未定義,則 公開名稱集合包括在模塊的名稱空間中找到的所有名稱 ,其中 不以下劃線 字符('_')開頭。 __all__應該包含整個公共API的 。它是 旨在避免意外 導出不屬於 API的項目(例如 導入並在 模塊中使用的庫模塊)。

相關問題