进行此类导入的正确方法是什么
What is the right way to do such import
这是我当前的文件夹结构
└── Main folder/
├── subfolder/
│ ├── subfolder_function.py
│ └── subfolder_function2.py
└── main.py
screenshot
这些是每个文件的内容
subfolder_function2.py
def subfolder_function2():
print("Hey I'm subfolder_function2.py")
subfolder_function.py
from subfolder_function2 import subfolder_function2
def my_function_from_subfolderfunc2():
subfolder_function2()
main.py
from subfolder.subfolder_function import my_function_from_subfolderfunc2
if __name__ == '__main__':
print(my_function_from_subfolderfunc2()))
为什么我总是收到此错误:
Traceback (most recent call last):
File "C:\R24\Main folder\main.py", line 1, in <module>
from subfolder.subfolder_function import my_function_from_subfolderfunc2
File "C:\R24\Main folder\subfolder_function.py", line 1, in <module>
from subfolder_function2 import subfolder_function2
ModuleNotFoundError: No module named 'subfolder_function2'
从 subfolder_function2.py 访问函数的正确方法是什么?
您需要在 subfolder_function.py
中使用相对导入来指定您希望导入来自同一目录。有关相对导入的详细信息,请参阅 docs
subfolder_function.py
from .subfolder_function2 import subfolder_function2
...
这是我当前的文件夹结构
└── Main folder/
├── subfolder/
│ ├── subfolder_function.py
│ └── subfolder_function2.py
└── main.py
screenshot
这些是每个文件的内容
subfolder_function2.py
def subfolder_function2():
print("Hey I'm subfolder_function2.py")
subfolder_function.py
from subfolder_function2 import subfolder_function2
def my_function_from_subfolderfunc2():
subfolder_function2()
main.py
from subfolder.subfolder_function import my_function_from_subfolderfunc2
if __name__ == '__main__':
print(my_function_from_subfolderfunc2()))
为什么我总是收到此错误:
Traceback (most recent call last):
File "C:\R24\Main folder\main.py", line 1, in <module>
from subfolder.subfolder_function import my_function_from_subfolderfunc2
File "C:\R24\Main folder\subfolder_function.py", line 1, in <module>
from subfolder_function2 import subfolder_function2
ModuleNotFoundError: No module named 'subfolder_function2'
从 subfolder_function2.py 访问函数的正确方法是什么?
您需要在 subfolder_function.py
中使用相对导入来指定您希望导入来自同一目录。有关相对导入的详细信息,请参阅 docs
subfolder_function.py
from .subfolder_function2 import subfolder_function2
...