当调用模拟的父类方法时,如何获取子Python类的名称?

2024-04-23 14:50:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个大型QT/Python应用程序中有大量对话框和向导,但无法确定哪个子类触发父类的exec_uu方法。使用mock或任何其他库是否仍然可以执行此操作?当然,我可以通过调试找到它,但我需要一种编程方式来实现

import mock
from PySide2 import QtWidgets

class CustomDialog(QtWidgets.QDialog):
    pass


class AnotherCustomDialog(QtWidgets.QDialog) :
    pass


def launch_custom_dialog() :
    dlg = CustomDialog() 
    dlg.exec_() 


with mock.patch.object(QtWidgets.QDialog, 'exec_') as mock_dialog:
    test_which_calls_launch_custom_dialog()
    if mock_dialog.called:
        # How do I find the name of the child? I.e. CustomDialog

Tags: theimport应用程序custompassqtlaunchmock
1条回答
网友
1楼 · 发布于 2024-04-23 14:50:52

如果您自己也这么叫:

def launch_custom_dialog() :
    dlg = CustomDialog()    # or could be any of your custom dialogs
    dlg.exec_()
    return dlg

然后,您可以创建自己的中间基类:

class CustomDialogBase(QtWidgets.QDialog):
    def exec_(self, *args, **kwargs):
        self.note_caller = self
        return super().exec_(*args, **kwargs)

class CustomDialog(CustomDialogBase):
    pass
class AnotherCustomDialog(CustomDialogBase) :
    pass

现在,您可以检查它是哪个子类:

dlg = launch_custom_dialog()
print(dlg.note_caller)

相关问题 更多 >