在一个包中,有没有办法直接访问模块,而不是通过包名?
In a package, is there a way to directly access modules, not via the package name?
考虑包含文件 __init__.py
、module_a.py
和 module_b.py
.
的目录 mypackage
如果 module_a
想要访问 module_b
,则必须执行 import mypackage.module_b
或 import module_b from mypackage
。只是 import module_b
失败了。
首先:为什么?
其次:这是个问题吗?
第三:如果是,最好的处理方法是什么?
Python 3 使用绝对导入;任何非限定名称都被视为顶级模块或包。
如果要从包内导入,请使用 .
相关包前缀; .
是当前包,..
父包,等等
因此,在您的 mypackage
包中,您可以通过以下方式访问其他模块:
from . import module_b
参见Intra-package References section of the Python tutorial and the import
statement reference。
考虑包含文件 __init__.py
、module_a.py
和 module_b.py
.
mypackage
如果 module_a
想要访问 module_b
,则必须执行 import mypackage.module_b
或 import module_b from mypackage
。只是 import module_b
失败了。
首先:为什么?
其次:这是个问题吗?
第三:如果是,最好的处理方法是什么?
Python 3 使用绝对导入;任何非限定名称都被视为顶级模块或包。
如果要从包内导入,请使用 .
相关包前缀; .
是当前包,..
父包,等等
因此,在您的 mypackage
包中,您可以通过以下方式访问其他模块:
from . import module_b
参见Intra-package References section of the Python tutorial and the import
statement reference。