繁体   English   中英

Python:如何导入与子包具有相同名称的模块?

[英]Python: how to import a module which has the same name as a subpackage?

我还没有遇到过这个问题,但我很好奇如何导入一个与子包具有相同名称的模块。 例如,可能的模块结构可能如下所示:

mymodule\
    __init__.py
    string.py

现在,如果我需要mymodule.string子包以及从同一目录中的包中的每个Python发行版提供的string模块,例如__init__.py ,该怎么办? 下面的代码行中的所有进口分装。

from   .                import string
import mymodule.string  as string
import string

在Python 2.5或2.6中,您可以使用:

>>> from __future__ import absolute_import

这告诉Python所有非明确相关的导入都应该被视为绝对的。 即,使用此声明后,您可以使用以下命令访问内置字符串模块和您自己的字符串模块:

>>> import string as the_builtin_string_module
>>> from . import string as my_package_string_module

我相信这成为Python 2.7(和Python 3.0)的默认设置。

有关详细信息,请参阅: http//www.python.org/dev/peps/pep-0328/#rationale-for-absolute-imports

您不必将其作为顶级导入导入。

只需import mymodule.stringfoo = mymodule.string.baz()等。

如果你真的想把子包用作string ,你可以import它作为string import ,但首先要像import string as builtinstring一样执行import string as builtinstring

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM