[英]Python Import Error (ModuleNotFoundError) when importing a function from a module that imports a class from another module
My file structure looks like: 我的文件结构如下:
/dir/
main.py
/src/
functionsfile.py
classfile.py
The functionsfile
has a function that uses the class created in the classfile
. functionsfile
有一个函数,它使用在类classfile
创建的classfile
。 I import that class with 我导入该类
from classfile import ClassName
(I've also tried importing *
). (我也试过导入
*
)。
Just testing the function in the functionsfile
with a print
statement, it appears to find the class module and use the ClassName
just fine, but then when I import
that function from functionsfile
into the main.py
script, it gives me the error: 只是使用
print
语句测试函数文件中的functionsfile
,它似乎找到类模块并使用ClassName
就好了,但是当我import
函数从functionsfile
导入main.py
脚本时,它给了我错误:
ModuleNotFoundError: No module named 'classfile'
I tried importing the function with both: 我尝试用两者导入函数:
from functionsfile import function
and 和
from functionsfile import *
I'm at a loss for why this is happening? 我为何会发生这种情况感到茫然?
It appears you are missing __init__.py file. 看来你缺少__init__.py文件。 Try importing after adding that in your /src/ folder.
在/ src /文件夹中添加后尝试导入。
Try 尝试
from src.classfile import ClassName
It would also be better to change your directory structure. 更改目录结构也会更好。
/dir
/src
/class
classfile.py
functionsfile.py
main.py
As what Aquarius said you need to create a blank __init__.py
file inside src folder 正如Aquarius所说,你需要在src文件夹中创建一个空白的
__init__.py
文件
And try to import it as 并尝试将其导入为
from src.classfile import *
Inside your main.py
file 在你的
main.py
文件中
I hope it works for you : D 我希望它适合你:D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.