如何使用__init__.py?
我正在尝试了解 __init__.py 文件如何从不同目录打包和调用模块。
我有一个像这样的目录结构:
init_test\
__init__.py
a\
aaa.py
b\
bbb.py
在 aaa.py
中有一个名为 test
的函数
bbb.py
看起来像这样:
import init_test.a.aaa
if __name__ == "__main__":
init_test.a.aaa.test()
但这给了我ImportError:没有名为 a.aaa 的模块
我做错了什么?我尝试过从包结构上方的模块(而不是包内部)执行相同的基本操作,但这也不起作用?我的 __init__.py
I'm trying to learn how the __init__.py
file works for packaging and calling modules from different directories.
I have a directory structure like this:
init_test\
__init__.py
a\
aaa.py
b\
bbb.py
in aaa.py
there is a function called test
bbb.py
looks like this:
import init_test.a.aaa
if __name__ == "__main__":
init_test.a.aaa.test()
but this gives me ImportError: No module named a.aaa
What am I doing wrong? I've tried doing the same basic thing from a module above the package structure as opposed to inside the package and that did not work either? My __init__.py
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您还需要在 a 和 b 目录中包含 __init__.py
为了让您的示例首先工作,您应该将基目录添加到路径中:
You also need to have __init__.py in a and b directories
For your example to work first you should add your base directory to the path:
您必须将空的
__init__.py
添加到 a.那么a就被识别为init_test的子包,可以导入了。请参阅http://docs.python.org/tutorial/modules.html#packages然后将
import init_test.a.aaa
更改为import ..a.aaa
,它应该可以工作。正如 Achim 所说,这是一个相对导入,请参阅 http://docs .python.org/whatsnew/2.5.html#pep-328如果你真的想运行
bbb.py
,你必须将 init_test/ 放在你的 python 路径上,例如然后你可以开始
或者如果你在里面b/
You have to add an empty
__init__.py
into a. Then a is recognized as a sub package of init_test and can be imported. See http://docs.python.org/tutorial/modules.html#packagesThen change
import init_test.a.aaa
toimport ..a.aaa
and it should work. This is -- as Achim says -- a relative import, see http://docs.python.org/whatsnew/2.5.html#pep-328If you really want to run
bbb.py
, you have to put init_test/ on your python path, e.g.And then you can start
or if you are inside b/
__init__.py
需要位于您想要用作模块的所有文件夹中。在您的情况下,这也意味着init_test/a
和init_test/b
。__init__.py
needs to be in all folders that you want to use as modules. In your case, this meansinit_test/a
andinit_test/b
too.