Python 3 "Sideways"相对导入

标签 python python-3.x package relative-path relative-import

<分区>

我的文件结构如下

math/
    snippets/
        numerical_methods.py
    homework1/
        main.py
    homework2/
        main.py

在作业 1 的 main.py 中,我想做

from ..snippets.numerical_methods import fixed-point-iteration

这样我就不必为每次使用该算法的作业都重新编写该算法。但是我收到错误消息“未加载父模块,无法执行相对导入”。我做错了什么?

最佳答案

您不能从层次结构中高于主脚本的内容导入,即高于 homework1 文件夹的内容。您可以做的是将您想要的脚本路径添加到导入路径中:

import sys
sys.path.append("..")
from snippets.numerical_methods import fixed-point-iteration

关于Python 3 "Sideways"相对导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26067972/

相关文章:

python - 如何像在 Matlab 中那样连接以下 python 代码?

python - Pandas 数据帧日期时间转换和最小/最大计算

r - ggfortify::autoplot 或 ggfortify::::autoplot 不工作

python - 通过 Python 运行 Windows CMD 命令

python - PIR 传感器运动检测计数写入 python 中的文本文件

windows - 在 Windows Server 2008 上使用 npm 安装 Node 包/依赖项

python - 什么是 Python 蛋?

python - 海象运算符 : if contition with strange results

python - 链接 ipython 小部件按钮和 slider 值

python - 如何在 python 中检索网络摄像头信息?