2009-08-19 55 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的项目(例如 导入并在 模块中使用的库模块)。

相关问题