【问题标题】:How to import a module in Python which is already imported in another file? [duplicate]如何在 Python 中导入已经导入另一个文件的模块? [复制]
【发布时间】:2017-07-07 10:19:33
【问题描述】:

在我的 gui.py 模块中,我有:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
        ...

如何在没有from gui import * 的情况下在我的main.py 中正确导入该模块中的所有内容我应该再次在我的from PyQt5 import QtCore ...from gui import QtCore ... 中使用吗?

【问题讨论】:

  • 您应该将每个 python 模块视为独立的,每个模块都需要导入才能使其正常工作。然后 Python 会做一些聪明的事情来缓存模块并避免编译它们两次。如此简短的回答包括所有使用它的模块中的 PyQt 导入。

标签: python pyqt


【解决方案1】:

一般来说,您不应该从本身只导入了它的模块中导入东西:

# gui.py
from PyQt5 import QtCore, QtGui, QtWidgets

def some_function():
    pass

你应该这样做:

# main.py
from PyQt5 import QtCore, QtGui, QtWidgets
from gui import some_function

唯一的例外是 __init__.py 为方便起见从其子模块中聚合模块的文件:

# some_module/__init__.py
from .submodule import some_function
from .other_submodule import some_other_function

然后

# main.py
from .some_module import some_function, some_other_function

由于不是gui 提供的模块,您应该直接从PyQt5 导入它们。

【讨论】:

  • 我在 gui 模块中也有其他类。
  • 你需要从gui导入的。但是不要通过gui从其他模块导入类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-01
  • 2018-04-23
  • 1970-01-01
  • 2022-12-10
  • 2018-05-15
  • 1970-01-01
相关资源
最近更新 更多