我在 __init__.py
文件中看到了 __all__
。它有什么作用?
最佳答案
与 __all__
相关联但未在此处明确提及的确切时间用来。它是一个字符串列表,定义在 from <module> import *
时将导出模块中的哪些符号。在模块上使用。
例如,foo.py
中的以下代码显式导出符号 bar
和 baz
:
__all__ = ['bar', 'baz']
waz = 5
bar = 10
def baz(): return 'baz'
然后可以像这样导入这些符号:
from foo import *
print(bar)
print(baz)
# The following will trigger an exception, as "waz" is not exported by the module
print(waz)
如果 __all__
上面被注释掉,这段代码将执行完成,作为 import *
的默认行为是从给定的命名空间中导入所有不以下划线开头的符号。
引用:https://docs.python.org/tutorial/modules.html#importing-from-a-package
注意: __all__
影响 from <module> import *
仅行为。 __all__
中未提及的成员仍然可以从模块外部访问,并且可以使用 from <module> import <member>
导入.
关于python - __all__ 在 Python 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44834/