为什么 *import ...* 和 *from x import y* 成语在这里表现如此不同?

Why do *import ...* and *from x import y* idioms behave so differently here?

我有这样的包结构:

- src
- src/main.py
- src/package1
- src/package1/__init__.py
- src/package1/module1.py
- src/package1/module2.py

... 其中 module2module1 的子类,因此 module1 被 [=34] 中的绝对导入路径引用=]module2.py.

也就是在src/package1/module2.py:

from package1.module1 import SomeClassFromModule1

问题出现在main.py脚本中:

## here the imports

def main():

        # create an instance of the child class in Module2

if __name__ == "__main__":
        main()

选项 1 有效。即在src/main.py:

from package1.module2 import SomeClassFromModule2

some_name = SomeClassFromModule2()

选项 2 无效。即在src/main.py:

import package1.module2.SomeClassFromModule2

some_name = package1.module2.SomeClassFromModule2()

...导致以下错误。

ModuleNotFoundError: No module named 'package1.module2.SomeClassFromModule2'; 'package1.module2' is not a package

那么为什么 importfrom ... import 成语之间存在这种差异?

很高兴得到一些澄清。

import x 关键字将 x 中的所有方法和 class 带到正在调用的文件中。

from x import y 这会从那个 .py 文件('x' 是文件在这里)而不是带来它拥有的所有方法。

在你 import package1.module2 的情况下,SomeClassForModule2() 已经被导入,因此你不需要写 import package1.module2.SomeClassFromModule2

这里我猜你想访问一个class,所以你需要创建一个对象才能访问它。

希望对您有所帮助

经过一些测试,我认为您无法使用 import your_module.your_class.

导入函数或 class

都是关于package, module, function and class:

# import module
>>>import os
<module 'os' from ooxx>

#use module of module (a litte weird)
>>>os.path
<module 'posixpath' from ooxx>

#import module of module (a litte weird)
>>>import os.path

#use function
>>>os.path.dirname
<function posixpath.dirname(p)>

# you cannot import a function (or class) by using 'import your.module.func'
# 'import ooxx' always get a module or package.
>>>import os.path.dirname
ModuleNotFoundError
No module named 'os.path.dirname'; 'os.path' is not a package                  

# instead of it, using 'from your_module import your_function_or_class'
>>>from os.path import dirname
<function posixpath.dirname(p)>