简体   繁体   English

package 中的 Python 疯狂模块导入

[英]Python crazy module import in a package

I'm inside a python package where there is A.py, B.py and an init file that allows me to import packages into the directory above.我在 python package 里面,里面有 A.py、B.py 和一个初始化文件,允许我将包导入到上面的目录中。

Thus, the content of my init file is as follows:因此,我的 init 文件的内容如下:

__path__ = __import__('pkgutil').extend_path(__path__, __name__)

I now want to import a class of B.py into A.py.我现在想将 B.py 的 class 导入 A.py。 I tried to use from B import myClass but it doesn't work.我尝试使用from B import myClass但它不起作用。 I also tried to add the file in the path by adding this line to the init file:我还尝试通过将此行添加到 init 文件中来将文件添加到路径中:

__path__.append(__file__)

How to add B.py to the path?如何将 B.py 添加到路径中?

--edit-- - 编辑 -

To clarify things, here is the structure of my packages and modules:为了澄清事情,这是我的包和模块的结构:

|app.py 
|package1
    |__init__.py
    |C.py
    |package2
        |__init__.py
        |A.py
        |B.py

In A.py I need to import classes from B.py and C.py在 A.py 中,我需要从 B.py 和 C.py 导入类

If this is python 3 related code...then really there's no need for an __init__.py anymore.如果这是 python 3 相关代码......那么真的不需要__init__.py了。

As long as your files that you want to import classes/functions from are within the same directory you should be able to just call in the file you want to do the import as this:只要您要从中导入类/函数的文件位于同一目录中,您就应该能够像这样调用要执行导入的文件:

 import B.myClass

or,或者,

 from . import myClass
 ### this imports all the classes and moduels from within the same directory 
 ### as you're currently in even if it has more than one file (but only imports myClass)

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

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