Python:导入包含的包 [英] Python: import the containing package

查看:67
本文介绍了Python:导入包含的包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在驻留在包中的模块中,我需要使用在该包的__init__.py中定义的功能.如何在包中的模块内导入包,以便可以使用该功能?

In a module residing inside a package, i have the need to use a function defined within the __init__.py of that package. how can i import the package within the module that resides within the package, so i can use that function?

在模块中导入__init__不会导入软件包,而是导入名为__init__的模块,导致具有不同名称的事物的两个副本...

Importing __init__ inside the module will not import the package, but instead a module named __init__, leading to two copies of things with different names...

有没有一种Python方式来做到这一点?

Is there a pythonic way to do this?

推荐答案

此外,从Python 2.5开始,可以进行相对导入.例如:

Also, starting in Python 2.5, relative imports are possible. e.g.:

from . import foo

http://docs.python.org/tutorial/引用modules.html#intra-package-references :

从Python 2.5开始,除了上述隐式相对导入之外,您还可以使用import语句的from模块导入名称形式编写显式相对导入.这些显式相对导入使用前导点表示相对导入中涉及的当前和父程序包.例如,在周围的模块中,您可以使用:

Starting with Python 2.5, in addition to the implicit relative imports described above, you can write explicit relative imports with the from module import name form of import statement. These explicit relative imports use leading dots to indicate the current and parent packages involved in the relative import. From the surrounding module for example, you might use:

from . import echo
from .. import formats
from ..filters import equalizer

这篇关于Python:导入包含的包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆