Search code examples
pythonoopclasspyqt4

How to call a method from one class in another class


I have two classes in a file.

Main class will have methods to update UI elements in that class. It creates an instance of another class.

I want to update UI in main class from the another class which was instanced.

class Add(QtGui.QMainWindow,Ui_AddShotDetails):

    def __init__(self):

        super(Add,self).__init__()
        self.setupUi(self)

    def addDetails(self):

        #Do some stuff and call method in Manager class
        Manager.EpiChange() # I get the error at this line

class Manager(QtGui.QMainWindow,Ui_ShotManager):

    def __init__(self):

        super(Manager,self).__init__()
        self.setupUi(self)
        self.AddWindow = Add()

    def EpiChange(self):

        Manager.EpiCode = str(self.cmb_Epi.currentText())
        # Update ui elements

    def addShot(self):

        self.AddWindow.show()

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    win = Manager()
    win.show()
    sys.exit(app.exec_())        

I get the following Traceback

Traceback (most recent call last):
  File "D:\Manager.py", line 18, in addDetails
    Manager.EpiChange()
TypeError: unbound method EpiChange() must be called with Manager instance as first argument (got nothing instead)

I tried making this method as classmethod using @classmethod if i use this i get below traceback

Traceback (most recent call last):
  File "D:\Manager.py", line 27, in EpiChange
    Manager.EpiCode = str(self.cmb_Epi.currentText())
AttributeError: type object 'Manager' has no attribute 'cmb_Epi'

Solution

  • def EpiChange(self)
    

    This signature means, that your method is an instance method and actually awaits an instance object as the first argument.

    If your method doesn't do anything with the class instance, but requires the class itself, it will be called "class method" and should await the class itself as the first argument.

    And, finally, if your method doesn't require neither of those (and you don't to have those self's in your method signature), but you still want it placed in some class - it is called "static method" in Python.

    Take a look at classmethod and staticmethod built-in functions (that could be used (and usually are used) as decorators).

    And about your code: looks like your Add class requires the Manager instance passed to it somehow, e.g.:

    class Add(QtGui.QMainWindow,Ui_AddShotDetails):
    
        def __init__(self, manager):
            super(Add,self).__init__()
            self.manager = manager
            self.setupUi(self)
    
        def addDetails(self):
            #Do some stuff and call method in Manager class
            self.manager.EpiChange() # I get the error at this line
    

    and then create Add instance it this way:

    self.AddWindow = Add(self)