__init__.py未检测到整个模块 [英] Entire module is not detected by __init__.py
问题描述
我有一个相对较小的python程序,其设置如下:
I have a relatively small python program which is setup like this
Root
--Network
--DTO
Lots of py files which contain classes.
Other py files in the project
在网络和DTO文件夹中,都有一个空的__init__.py
.
Both in the Network and the DTO folder there is an empty __init__.py
.
当我执行from Network import DTO
,import Network
,Import Network.DTO
时,我完全无法使用该模块.调试器说它完全是空的.根目录包含我实际上正在执行的py文件.
When I do from Network import DTO
, import Network
, Import Network.DTO
I cannot use the module at all. The debugger says it's completely empty. The root contains the py file I am actually executing.
Network和DTO文件夹中的__init__.py
文件都被编译为pyc
,而并非所有实际的python文件都被编译.
Both the the __init__.py
files in the Network and DTO folder are compiled to pyc
while all actual python files aren't.
有人知道我在做什么错吗?我正在使用python 2.7
Does anyone have any idea what I am doing wrong? I am using python 2.7
推荐答案
为此,您需要在__init__.py
中导入子模块.如果您有很多子模块,则很难为每个子模块添加导入.对于许多子模块(通常),请使用__all__
.
For that, you need to import the submodules in your __init__.py
. It becomes more difficult to add an import for every submodule if you have many, as you do. In the case of many submodules (and in general), use __all__
.
以下是Root/Network/DTO/__init__.py
的示例:
__all__ = [
'sample_module',
...
]
for module in __all__:
__import__('DTO.%s' % module)
现在您可以执行from Network.DTO import sample_module
.同样的想法也适用于您的其他模块.
Now you can do from Network.DTO import sample_module
. The same idea holds for your other modules, as well.
这篇关于__init__.py未检测到整个模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!