首页 > 解决方案 > 解决自己模块中的相对导入

问题描述

helloPython
  __init__.py
  
  myutil
    __init__.py
    mymaths.py

  service
    __init__.py
    cal.py

mymaths.py

def myadd(a, b):
    return a+b

cal.py

from ..myutil import mymaths #or any other similar import statement

sum = mymaths.myadd(3, 4)

在这里,在 cal.py 中,我想使用上面 mymaths.py 中定义的方法但是当我尝试导入时,当我在 VSCode 中“在终端中运行 Python 文件”时出现以下错误尝试了多种方法

  1. 第一种方法

    从 ..myutil 导入 mymaths

ImportError:尝试在没有已知父包的情况下进行相对导入

  1. 第二种方法

    从 helloPython.myutil 导入 mymaths

ModuleNotFoundError:没有名为“helloPython”的模块

标签: pythonpython-import

解决方案



推荐阅读