繁体   English   中英

将类导入另一个文件夹

[英]Importing a class in another folder

我的python目录有问题。

我有这样的结构:

  • 蟒蛇
    • 模块
      • 算法
        • cyphers
          • morse.py
    • 测试
      • 算法
        • cyphers
          • test_morse.py

当我尝试在测试中导入模块时,出现模块未找到错误。 我试图像这样导入:

parent_dir_name = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(parent_dir_name + "/../../../")

from modules.algorithms.cyphers.morse import *

我还在所有目录中都有init文件。 我正在尝试运行以下测试:

> python -m unittest discover ./tests

通常使用相对进口

from ....modules.algorithms.ciphers.morse import *

这样可以确保您导入正确的Morse文件,否则就有可能导入已安装的名为Morse的模块。

这是两个说明相对导入的示例,假设您有一个名为Simulation.py的文件,其中有一行

from .animals import Herbivore

在里面。 这将从与Simulation.py文件位于同一目录的文件中导入Herbivore类

现在,假设您是一个名为tests的文件夹,在此文件夹中有一个名为test_animals.py的文件,其中包含以下行

from ..animals import Herbivore

这将从位于tests文件夹上方的文件夹中的名为animals.py的文件导入Herbivore类。

最后,请注意(至少对于Python 3.6)不能运行使用相对导入的文件,而只能导入它。

如果使用__init__.py将目录标记为模块,则应该能够通过导入模块

from modules.algorithms.cyphers import morse

暂无
暂无

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

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