简体   繁体   English

python:带有“嵌套”模块的导入包

[英]python : imported packages with 'nested' modules

When i import modules , this nested scenario works fine.当我导入模块时,这个嵌套场景工作正常。 But when i try to import packages , i got inconsistent result.但是当我尝试导入包时,我得到了不一致的结果。 Here's the very simple case :这是一个非常简单的案例:

contents of my current folder :我当前文件夹的内容:

mypackages <directory>
   __init__.py 
   one.py
   two.py
   three.py

this is the script :这是脚本:

__init__.py :
import one

one.py :
import two

two.py :
import three

I'm expecting that i should be able to access two and three this way :我期待我应该能够通过这种方式访问两个三个

import mypackages
mypackages.one.two
mypackages.one.two.three

or in other word the logical level shoul be like this :或者换句话说,逻辑级别应该是这样的:

one
  two
    three

But when i do import mypackages , i got all the modules exposed at the same level :但是当我导入 mypackages 时,我将所有模块都暴露在同一级别:

>>> import mypackages
>>> print dir(mypackages)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 
'__path__', 'one', 'three', 'two']

It should only show one module , right ?它应该只显示one模块,对吗? I'm confused why it shows all one , two and three which means they are at the same level ( i can use mypackages.two and mypackages.three directly ).我很困惑为什么它显示所有one , twothree ,这意味着它们处于同一级别(我可以直接使用mypackages.twomypackages.three )。

Does anyone have any explaination ?有没有人有任何解释?

You should read this .你应该阅读这个

By putting the files at the same level, you put them is the same package level.通过将文件放在同一级别,您将它们放在相同的包级别。 In your case, you need to get this architecture:在您的情况下,您需要获得此架构:

mypackage
├── __init__.py
├── one.py  # contains "import two"
└── two
    ├── __init__.py
    ├── two.py  # contains "import three"
    └── three
        ├── __init__.py
        └── three.py

And then, you can access the package with:然后,您可以通过以下方式访问该包:

import mypackage.one
import mypackage.one.two
import mypackage.one.two.three

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

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