我正在使用 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
为什么这行得通? I though there needed to be __init__.py
files (empty ones would work) in both a
and b
for module.py
to be importable when the Python 路径指向 Playground
文件夹?
这似乎已经从 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
在 __init__.py
~/Playground/a
和 ~/Playground/a/b
它工作正常。
原文由 wujek 发布,翻译遵循 CC BY-SA 4.0 许可协议
Python 3.3+ 具有 隐式命名空间包,允许它创建没有
__init__.py
文件的包。使用
__init__.py
文件的旧方法仍然像在 Python 2 中一样工作。