簡體   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