Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

python - 有人可以用Python解释__all__吗?(Can someone explain __all__ in Python?)

I have been using Python more and more, and I keep seeing the variable __all__ set in different __init__.py files.

(我越来越多地使用Python,并且不断看到在不同的__init__.py文件中设置了变量__all__ 。)

Can someone explain what this does?

(有人可以解释这是什么吗?)

  ask by varikin translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Linked to, but not explicitly mentioned here, is exactly when __all__ is used.

(链接到__all__确切时间是在此处,但未明确提及。)

It is a list of strings defining what symbols in a module will be exported when from <module> import * is used on the module.

(它是一个字符串列表,用于定义在模块上使用from <module> import *时将在模块中导出哪些符号。)

For example, the following code in a foo.py explicitly exports the symbols bar and baz :

(例如, foo.py的以下代码显式导出符号barbaz :)

__all__ = ['bar', 'baz']

waz = 5
bar = 10
def baz(): return 'baz'

These symbols can then be imported like so:

(然后可以像下面这样导入这些符号:)

from foo import *

print(bar)
print(baz)

# The following will trigger an exception, as "waz" is not exported by the module
print(waz)

If the __all__ above is commented out, this code will then execute to completion, as the default behaviour of import * is to import all symbols that do not begin with an underscore, from the given namespace.

(如果上面的__all__被注释掉,则此代码将执行完成,因为import *的默认行为是从给定的命名空间中导入所有不以下划线开头的符号。)

Reference: https://docs.python.org/tutorial/modules.html#importing-from-a-package

(参考: https : //docs.python.org/tutorial/modules.html#importing-from-a-package)

NOTE: __all__ affects the from <module> import * behavior only.

(注意: __all__影响from <module> import *行为。)

Members that are not mentioned in __all__ are still accessible from outside the module and can be imported with from <module> import <member> .

(__all__中未提及的成员仍然可以从模块外部访问,并且可以通过from <module> import <member> 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...