我使用的是Python 3.5.1 . 我在这里阅读了文档和包装部分:https://docs.python.org/3/tutorial/modules.html#packages
现在,我有以下结构:
/home/wujek/Playground/a/b/module.py
module.py
:
class Foo:
def __init__(self):
print('initializing Foo')
现在,在 /home/wujek/Playground
:
~/Playground $ python3
>>> import a.b.module
>>> a.b.module.Foo()
initializing Foo
<a.b.module.Foo object at 0x100a8f0b8>
同样,现在在家里, Playground
的超级文件夹:
~ $ PYTHONPATH=Playground python3
>>> import a.b.module
>>> a.b.module.Foo()
initializing Foo
<a.b.module.Foo object at 0x10a5fee10>
实际上,我可以做各种各样的事情:
~ $ PYTHONPATH=Playground python3
>>> import a
>>> import a.b
>>> import Playground.a.b
为什么这样做?当Python路径指向 Playground
文件夹时, a
和 b
中的 __init__.py
文件需要 __init__.py
文件(空文件才有效)吗?
这似乎已经从Python 2.7改变了:
~ $ PYTHONPATH=Playground python
>>> import a
ImportError: No module named a
>>> import a.b
ImportError: No module named a.b
>>> import a.b.module
ImportError: No module named a.b.module
~/Playground/a
和 ~/Playground/a/b
中的 __init__.py
可以正常工作 .
2 回答
Python 3.3有Implicit Namespace Packages,允许它创建一个没有
__init__.py
文件的包 .使用
__init__.py
文件的旧方法仍然可以像在Python 2中那样工作 .@迈克的答案是正确的,但太不精确了 . 确实,Python 3.3支持隐式命名空间包,它允许它创建一个没有
__init__.py
文件的包 .但是,这仅适用于 EMPTY init.py 文件 . 因此不再需要 EMPTY init.py 文件,可以省略 . 如果要将模块导入包中,仍需要 init.py 文件列出所有导入 .
目录结构示例:
child_package
中的__init__
文件: