根据 python 中的 Class 名称快速找到要导入的模块

Quickly find module to import based on Class name in python

我正在学习和使用 Python 和 Pyside2(QT5 的包装器)。

我问的是 PySide2,但可能的答案可以帮助我处理每个包。

基本上,我正在学习一个教程,其中我阅读了我在此处报告的部分代码:

app = QApplication(sys.argv)
pixmap = QPixmap(":/splash.png")
splash = QSplashScreen(pixmap)
splash.show()
app.processEvents()
window = QMainWindow()
window.show()
splash.finish(window)

因为我是初学者,教程没有提到我必须导入哪个模块才能使用 QSplashScreen,所以我一直在浪费时间询问 Google 我必须导入哪个模块导入以使用某种方法或 Class,在本例中为 QSplashScreen。

例如,为了在我的代码中使用 QLabel,我必须输入

from PySide2.QtWidgets import QLabel

我的理解是 QLabel 在 QtWidgets“内部”,而 QtWidgets 又在 PySide2“内部”。

现在我的问题是 Python 中是否存在我可以做的事情(在 REPL 中)

import magic
magic.findInTheFollowingPackage("PySide2").somethingINeed("QLabel")
>>> PySide2.QtWidgets # output

然后我可以得到

的答案
magic.findInThisPackage("PySide2").somethingINeed("QSplashScreen")

你可以这样做:

from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *

def get_import_of(cls):
    print('from', cls.__module__, 'import', cls.__name__)

打印任何 class 的导入语句。

>>> get_import_of(QSplashScreen)
from PySide2.QtWidgets import QSplashScreen

>>> get_import_of(QPixmap)
from PySide2.QtGui import QPixmap

可以扩展函数以支持多个参数:

def get_import_of(*args):
    d = {cls.__module__: [] for cls in args}
    for cls in args:
        d[cls.__module__].append(cls.__name__)
    print('\n'.join(f'from {k} import ' + ', '.join(v) for k, v in d.items()))


>>> get_import_of(QSplashScreen, QPixmap, QLabel, QTimer)
from PySide2.QtWidgets import QSplashScreen, QLabel
from PySide2.QtGui import QPixmap
from PySide2.QtCore import QTimer

或者在交互式 shell 中输入 class 名称。

>>> QSplashScreen
<class 'PySide2.QtWidgets.QSplashScreen'>