解决自己模块中的相对导入
Resolve relative import in own module
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 终端中的文件”尝试了多种方式
第一种方法
从 ..myutil 导入 mymaths
ImportError: attempted relative import with no known parent package
第二种方法
从 helloPython.myutil 导入 mymaths
ModuleNotFoundError: No module named 'helloPython'
Relative imports in Python 2.7 and ImportError: attempted relative import with no known parent package helped me to understand. Thanks to @napuzba
和 @martineau
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 终端中的文件”尝试了多种方式
第一种方法
从 ..myutil 导入 mymaths
ImportError: attempted relative import with no known parent package
第二种方法
从 helloPython.myutil 导入 mymaths
ModuleNotFoundError: No module named 'helloPython'
Relative imports in Python 2.7 and ImportError: attempted relative import with no known parent package helped me to understand. Thanks to @napuzba 和 @martineau