import"和"import *"有什么区别?

6 投票
1 回答
679 浏览
提问于 2025-04-15 13:42
"""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'
>>> 

1 个回答

21

以“_”开头的变量(下划线)不是公共名称,在使用from x import *时不会被导入。

这里的_test__test都不是公共名称。

根据导入语句的描述:

如果用星号('*')替换标识符列表,所有在模块中定义的公共名称都会被绑定到导入语句的本地命名空间中。

一个模块定义的公共名称是通过检查模块的命名空间中是否有一个名为__all__的变量来确定的;如果定义了这个变量,它必须是一个字符串序列,这些字符串是该模块定义或导入的名称。__all__中列出的名称都被视为公共名称,并且必须存在。如果没有定义__all__,公共名称的集合包括所有在模块命名空间中找到的、不以下划线('_')开头的名称。 __all__应该包含整个公共API。它的目的是避免意外导出那些不是API一部分的项目(比如在模块内部导入和使用的库模块)。

撰写回答