为什么从同一目录中的模块导入时必须在模块前加一个点?

Why do I have to put a dot before module when import it from the module within same directory?

正在学习Python,感觉import函数和Java有些不一样。

我的代码层次如下:

test.py 运行如上。当我将 submod.py 重写为:

from anothersubmod import res

Python 给我一个错误,说找不到 anothersubmod...

我猜 submodanothersubmod 在同一个目录中,因此它们应该使用模块(文件)名称相互引用,为什么我必须在 [=21= 之前添加一个点]?

Java 等效项是在任何地方显式引用 pack,例如:

import pack.anothersubmod.MyClass;

Python 等价于:

from pack.anothersubmod import MyClass

正确 Python 并且实际上更喜欢这种风格。 Python 也可以在 import 语句中使用相对路径(from . 风格),但它们往往会造成更多的混乱。

PEP 8 建议尽可能在任何地方使用绝对导入:

Absolute imports are recommended, as they are usually more readable and tend to be better behaved (or at least give better error messages) if the import system is incorrectly configured.