在包\uu init_u.py文件中定义的导入范围是什么?

2024-10-04 01:24:17 发布

您现在位置:Python中文网/ 问答频道 /正文

对于一个项目,我不得不从C++切换到Python,但在完全理解^ {< CD1>}文件方面遇到了一些困难。我在__init__.py文件中找到了以下文档:

为了更熟悉__init__.py文件的工作方式,我在python2.7和3.6.5中做了一些测试。为此,我使用了“PythonCentral”测试包(见链接2):

package overview

现在我了解了__init__.py文件的以下内容:

  • 导入模块或子包模块时,__init__.py文件将执行。在
  • __init__.py可用于重载包__all__方法。在
  • __init__.py可用于定义导入顺序
  • __init__.py可用于使类在包和子包级别上可用。在

使用主文件范围内的不同模块和类似乎如文档中所述。然而,当我试图使用在另一个子包模块中定义的类时,我遇到了麻烦。在python 2.7中,在subanimals子包中创建了以下__init__.py文件:

from Mammals import Mammals

print "subpackage __init__.py executed"

接下来我在小鸟.py模块:

^{pr2}$

运行以下主脚本时:

    from animals.subanimals import Birds

test = Birds()
test.printMembers()

我一直不知道哺乳动物的全球名字。我可以在Python2.7中解决这个问题,方法是在小鸟.py. 在

__init__.py是否只导入主脚本作用域级别的包和类,因此不导入小鸟模块还是我做错了什么?在


Tags: 模块文件方法from文档pyhttpsimport
1条回答
网友
1楼 · 发布于 2024-10-04 01:24:17

我的问题可以在@jornsharpe的评论中找到答案。在

Each individual file must be valid on its own, defining all appropriate imports. init.py is for aggregating multiple files in a directory into a single module; think of it as grouping and passing attributes up to the parent, not down to the other files in that directory.

相关问题 更多 >