如何导入已导入另一个文件的Python模块?
问题描述:
在我gui.py模块我有:如何导入已导入另一个文件的Python模块?
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
...
如何正确地从我的main.py该模块导入的一切,而不from gui import *
我应该再次使用我的from PyQt5 import QtCore ...
或from gui import QtCore ...
?
答
一般情况下,你不应该从它本身只是其导入模块导入的东西:
# 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
由于the're不gui
提供的模块,你应该直接从PyQt5
导入。
+0
我也有gui模块中的其他类。 –
+0
那些你需要从'gui'导入。但不要通过'gui'从其他模块导入类。 –
你应该把每个python模块当作独立的模块,每一个python模块都需要导入才能工作。 Python然后聪明的东西来缓存模块,并避免两次编译它们。所以简短的回答包括所有使用它的模块中的PyQt导入。 –