__init__.py 发生了怎样的变化?

How has __init__.py changed?

我正在将我的 Python 2.7 内容(工作正常)迁移到 3.4.3。

在我的 C:\Python34\Lib\MyLibs 文件夹中,我有两个文件:__init__.pyutils.py 从 Python 2.7 中的同一文件夹复制而来。在 utils.py 中,我在顶部附近有这条线:

from __init__ import *

在 3.4.3 中,当我执行 import MyLibs.utils 时出现错误:

ImportError: No module named __init__

但是,我可以确认 __init__.py 中的代码在第一次导入语句 运行 时成功执行。

我可以知道如何在 Python 中导入或访问在 __init__.py 中声明的变量 3.

Python 3 使用绝对导入,其中不合格的导入总是作为顶级包查找。你没有这样的包裹。

您将改用显式相对导入:

from . import *

或使用绝对导入

from packagename import *

并不是说您应该首先在 Python 2 中使用 from __init__ import * 。你会用 from packagename import * 来代替。

您可以在 Python 2 中启用绝对导入模型:

from __future__ import absolute_imports

参见 PEP 328 - Imports: Multi-Line and Absolute/Relative

不过,您可能还会遇到其他问题。移植不是那么简单,请阅读 Porting to Python 3 book. This issue is a common migration problem.

中的问题