【问题标题】:Calling a method from another class, while beeing in a method which already was called from the first class从另一个类调用一个方法,同时在一个已经从第一个类调用的方法中
【发布时间】:2020-05-25 20:43:09
【问题描述】:

我知道有很多类似的问题,但是:对于这种情况,我没有找到正确的提示。

概述

我正在编写一个 GUI (PyQt5)。有一个主类Ui_MainWindow() 和一个类Algorithm() 进行一些计算。

首先调用Ui_MainWindow(),然后调用实例Algorithm()

我的想法:Ui_MainWindow() 中,我调用了一个在Algorithm() 中定义的方法,称为def update(self)。现在,在def update(self) 中,我想调用一个方法def move(self),它又在第一类Ui_MainWindow() 中。

我的问题:要由另一个类调用一个方法,我需要先实例化它,但我不能实例化一个类两次(在开始和第二个类中),因为那会抛出无穷无尽的错误。

示例:

class Algorithm():
    def __init__(self, job_list):
        self.job_list = job_list
    def update(self):
        main = Ui_MainWindow() # this is the problem, I can not do this twice
        main.move()

class Ui_MainWindow():
    def __init__(self, *args, **kwargs):
        super(Ui_MainWindow, self).__init__(*args, **kwargs)
        self.setupUi()
    def setupUi(self):
        """ random code """
    def move(self):
        """ random code """

if __name__ == "__main__":
    main = Ui_MainWindow() # And I need it here. 
    main.show()

如果我的解释不清楚,请告诉我。

感谢您的帮助。

【问题讨论】:

    标签: python class methods


    【解决方案1】:

    我认为您的主窗口没有从 QMainWindow 继承这一事实会给您带来问题,但暂时不考虑这一点,我建议您嵌套对象的方法如下:

    # define Ui_MainWindow first
    
    class Algorithm():
        def __init__(self, job_list):
            self.job_list = job_list
            self.main_window = Ui_MainWIndow()
    
        def show(self):
            self.main_window.show()
    
        def update(self):
            self.main_window.move()
    
    if __name__ == "__main__":
        # generate job_list somehow?
        algo = Algorithm(job_list)
        algo.show()
    

    【讨论】:

      【解决方案2】:

      您可以添加 UI_MainWindow 对象作为更新函数的参数,如下所示:

      def update(self, ui_Window):
          main = ui_Window
          main.move()
      

      然后,要从您的 UI_MainWindow 类中调用它,您可以这样做:

      algorithm = Algorithm(job_list)
      algorithm.update(self)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-14
        • 2014-02-07
        • 2014-11-07
        • 2013-10-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多