简体   繁体   English

如何在Python 3中创建包? ModuleNotFoundError

[英]How to create packages in Python 3? ModuleNotFoundError

I am following the easy guide on the Python Central to create a package for my code: 我按照Python Central上的简易指南为我的代码创建一个包:

https://www.pythoncentral.io/how-to-create-a-python-package/ https://www.pythoncentral.io/how-to-create-a-python-package/

So my directory structure is: 所以我的目录结构是:

main.py
pack1/
         __init__.py
         Class1.py

In the main.py file I import and use Class1 as: main.py文件中,我导入并使用Class1

from pack1 import Class1
var1 = Class1()

In the __init__.py file I have written: __init__.py文件中我写了:

import Class1 from Class1

I followed the guide exactly and still get the error: 我完全按照指南,仍然得到错误:

ModuleNotFoundError: No module named 'Class1' (in __init__.py)

Python 3 has absolute imports . Python 3具有绝对导入 Change your __init__.py to : __init__.py更改为:

from .Class1 import Class1

The leading dot indicates that this module is found relative to the location of __init__.py , here in the same directory. 前导点表示相对于__init__.py的位置找到此模块,此处位于同一目录中。 Otherwise, it looks for a standalone module with this name. 否则,它会查找具有此名称的独立模块。

PEP 328 gives all details. PEP 328提供了所有细节。 Since Python 3.0 this is the only way : 从Python 3.0开始,这是唯一的方法

Removed Syntax 删除了语法

The only acceptable syntax for relative imports is from .[module] import name . 相对导入唯一可接受的语法from .[module] import name All import forms not starting with . 所有import表单都不以. are interpreted as absolute imports. 被解释为绝对进口。 (PEP 0328) (PEP 0328)

The file Class1.py contains this code: 文件Class1.py包含以下代码:

class Class1:
    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM