python 将所有模块导入到一个 python 文件中,我们可以在另一个文件中导入该文件?

python import all modules to a python file which we can import in another file?

我是 python 的新手。我有一些 python 脚本需要导入不同的 python 模块。

是否可以

  1. 将所有模块导入到一个文件中,比如 modules.py
  2. 并将此 modules.py 导入所有脚本,这样就不需要为每个脚本导入模块了?

提前致谢

在我的模块中:

import module1
import module2

在应用程序中:

from mymodules import *

但这真的值得吗? python 的禅宗指出:

Explicit is better than implicit.

复制文件顶部的一些行并不太麻烦。

至少有 4 种导入模块的方法:

import X, imports the module X: this way you can use X.whatever to refer to things defined in module X.

from X import *, imports the module X: this way you can simply use a plain name to refer to things defined in module X.

from X import x, y, z:  you can now use x and y and z in the current name space.

X = __import__(‘X’) works like import X but this time the module name is a string. Use it it you don't know the module name before execution. 

将命名空间视为 Python 字典结构,其中字典键表示名称,字典值表示对象本身。使用 import 你可以在你的命名空间中命名模块。

就是说,您可以完美地将模块导入脚本中(将其命名为 importer os 之类的东西),然后导入 "importer",一切都将在您的命名空间中。 这是个好主意吗?可能不是,因为在不同的模块中发现相同的名称(方法、函数或其他)很常见,如果发生这种情况,就会出现歧义。