简体   繁体   English

导入自定义模块python时省略子目录

[英]Omitting subdirectories when import custom modules python

crispy13/
    __init__.py
    core/
        __init__.py
        ecf.py

How can i load the ecf module in the following ways?如何通过以下方式加载 ecf 模块?

from crispy13 import ecf
OR
from crispy13.ecf import *

instead of代替
from crispy13.core.ecf import *

crispy13/__init__.py中将包导入为

from .core import ecf

like sahasrara62 said it can be done in the following manner就像sahasrara62说的可以通过以下方式完成

in crispy13/__init__.py import your module ascrispy13/__init__.py您的模块导入为

from .core import ecf

you can also make use of __all__ variable in your __init__.py file.您还可以在__init__.py文件中使用__all__变量。

This is a very good way of importing modules/functions/classes.这是一个非常好的导入模块/函数/类的方式。

Little bit insight to why we do imports in this way.对我们为什么以这种方式进行导入的一点见解。
Let's suppose you are using a third-party library/package and there are some implementation changes in the module假设您正在使用第三方库/包,并且模块中有一些实现更改

  1. changes the place of the function/class that you are importing更改您正在导入的函数/类的位置
  2. removed a module and put its contents into another module of the same package删除一个模块并将其内容放入同一包的另一个模块中

then your import will break.那么您的导入将中断。

That's why all third party libraries/packages include all of their consumable functions/classes/modules in the root __init__.py file of their package.这就是为什么所有第三方库/包都在其包的根__init__.py文件中包含所有可使用的函数/类/模块的原因。

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

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