为什么这个与导入相关的代码在\uuu init \uuuuuuuy.py文件中工作,而不是在不同的.py文件中工作?

2024-04-25 04:35:49 发布

您现在位置:Python中文网/ 问答频道 /正文

让我们把这个__init__.py放在Python3包中:

from .mod1 import *
from .mod2 import *
from .mod3 import *
__all__ = mod1.__all__ + mod2.__all__ + mod3.__all__

代码看起来非常简单,并且实现了预期的功能:它从模块mod1、mod2和mod3导入这些模块放入其__all__列表的所有符号,然后创建所有三个__all__列表的摘要。你知道吗

我尝试在一个模块中运行完全相同的代码,即不在__init__.py中运行。它导入了三个模块,但是mod1mod2mod3是未定义的变量。你知道吗

(顺便说一句,如果在原始的__init__.py上运行pylint,也会出现此错误。)

同一语句from .mod1 import *__init__.py中执行时会创建mod1对象,但不会在其他地方创建它。为什么?你知道吗

__init__.py是一个特殊的文件,但直到现在,我还以为只有它的名字是特殊的。你知道吗


Tags: 模块代码frompyimport功能列表init
1条回答
网友
1楼 · 发布于 2024-04-25 04:35:49

根据documentation,这是预期的行为:

When a submodule is loaded using any mechanism (e.g. importlib APIs, the import or import-from statements, or built-in __import__()) a binding is placed in the parent module’s namespace to the submodule object. For example, if package spam has a submodule foo, after importing spam.foo, spam will have an attribute foo which is bound to the submodule.

换句话说,当您在模块中执行from .whatever import something时,您将神奇地获得绑定到模块whatever属性。当然,您可以在__init__.py中访问模块自己的属性,就好像它们在那里被定义为变量一样。当你在另一个模块时,你不能这样做。从这个意义上说__init__.py确实是特别的。你知道吗

相关问题 更多 >