gpt4 book ai didi

python - 为什么 "import"与 "import *"有区别?

转载 作者:太空狗 更新时间:2023-10-29 22:03:17 27 4
gpt4 key购买 nike

"""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'
>>>

最佳答案

带有前导“_”(下划线)的变量不是公共(public)名称,并且在使用from x import * 时不会被导入。

在这里,_test__test 不是公共(public)名称。

来自import语句说明:

If the list of identifiers is replaced by a star ('*'), all public names defined in the module are bound in the local namespace of the import statement..

The public names defined by a module are determined by checking the module’s namespace for a variable named __all__; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in __all__ are all considered public and are required to exist. If __all__ is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ('_'). __all__ should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).

关于python - 为什么 "import"与 "import *"有区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1297766/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com