简体   繁体   English

从不同的文件夹级别导入类 - Python

[英]Import a class from different folder levels - Python

I am writing a sequence to sequence model and I have the following directory structure我正在写一个序列到序列模型,我有以下目录结构

MyProject/
     models/ 
          - __init__.py
          - Encoder.py
     train/
          - __init__.py
          - Train.py

While in Train.py, I cannot import the classes BiDirectionalEncoder from Encoder.py despite trying to use the following syntax在 Train.py 中,尽管尝试使用以下语法,但我无法从 Encoder.py 导入类 BiDirectionalEncoder

from models.Encoder import BiDirectionalEncoder 

For the line above I get the error " ModuleNotFoundError: No module named 'models'"对于上面的行,我收到错误“ModuleNotFoundError: No module named 'models'”

from ..models.Encoder import BiDirectionalEncoder

For the last line I get the error "ImportError: attempted relative import with no known parent package"对于最后一行,我收到错误“ImportError:在没有已知父包的情况下尝试相对导入”

Is there are neat way to fix this?有没有巧妙的方法来解决这个问题? I dont want to use any sys.path.append() to force paths to be added I am using Python 3.7.6 in Spyder 4.0.1 Thanks!我不想使用任何 sys.path.append() 来强制添加路径我在 Spyder 4.0.1 中使用 Python 3.7.6 谢谢!

在同一个包中,您可以进行相对导入,但由于您要离开当前包,因此需要进行绝对导入。

from MyProject.models.Encoder import BiDirectionalEncoder 

If you are using any IDE (eg. pycharm) you need to set (my project) as source boot directory else you need to check your BASE_DIR in settings.py如果您使用任何 IDE(例如 pycharm),您需要将(我的项目)设置为源启动目录,否则您需要在 settings.py 中检查您的 BASE_DIR

and then you will be able to import the model.然后你就可以导入模型了。

from models.Encoder import BiDirectionalEncoder from models.Encoder import BiDirectionalEncoder

and yes if you want to access module from other environment below is the link for ways of accessing and sharing modules.是的,如果您想从其他环境访问模块,下面是访问和共享模块方式的链接。

python module:- importing(accessing) creating and sharing python模块:-导入(访问)创建和共享

hope this will resolve your issue.希望这能解决您的问题。

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

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