如何在 Python 3 中创建包?模块未找到错误
How to create packages in Python 3? ModuleNotFoundError
我正在按照 Python Central 上的简单指南为我的代码创建一个包:
https://www.pythoncentral.io/how-to-create-a-python-package/
所以我的目录结构是:
main.py
pack1/
__init__.py
Class1.py
在 main.py
文件中,我将 Class1
导入并用作:
from pack1 import Class1
var1 = Class1()
在__init__.py
文件中我写了:
import Class1 from Class1
我完全按照指南操作,但仍然出现错误:
ModuleNotFoundError: No module named 'Class1' (in __init__.py)
Python3个有absolute imports。将您的 __init__.py
更改为:
from .Class1 import Class1
前导点表示此模块是相对于 __init__.py
的位置找到的,此处位于同一目录中。否则,它会查找具有此名称的独立模块。
PEP 328 gives all details. Since Python 3.0 this is the only way:
Removed Syntax
The only acceptable syntax for relative imports is from .[module] import name
. All import
forms not starting with .
are interpreted as absolute imports. (PEP 0328)
文件 Class1.py
包含此代码:
class Class1:
pass
我正在按照 Python Central 上的简单指南为我的代码创建一个包:
https://www.pythoncentral.io/how-to-create-a-python-package/
所以我的目录结构是:
main.py
pack1/
__init__.py
Class1.py
在 main.py
文件中,我将 Class1
导入并用作:
from pack1 import Class1
var1 = Class1()
在__init__.py
文件中我写了:
import Class1 from Class1
我完全按照指南操作,但仍然出现错误:
ModuleNotFoundError: No module named 'Class1' (in __init__.py)
Python3个有absolute imports。将您的 __init__.py
更改为:
from .Class1 import Class1
前导点表示此模块是相对于 __init__.py
的位置找到的,此处位于同一目录中。否则,它会查找具有此名称的独立模块。
PEP 328 gives all details. Since Python 3.0 this is the only way:
Removed Syntax
The only acceptable syntax for relative imports is
from .[module] import name
. Allimport
forms not starting with.
are interpreted as absolute imports. (PEP 0328)
文件 Class1.py
包含此代码:
class Class1:
pass