Search code examples
pythoninitializationargumentssuperclass

python superclass initialization arguments


I encounter a problem on how to write arguments for super class initialization. Theclass App1 needs to inherit from two other classes. I initialized all the arguments from the base classes at class App1, but the error says that I have too many args. I'm wondering why? Basically, I put all the arguments from the base classes in the super init. The 3 classes are written as multiple windows, and a Button commands the class jumps one by one. So I call the main() as myApp = Welcome(root, csv_name_ses, csv_name_sub).

Thanks for your help!

class question(object): #first window
     def __init__(self, algorithmIndex, initX, mid_loss_list = None, mid_gain_list = None):
          self.initX = initX
          self.algorithmIndex = algorithmIndex
          self.mid_gain_list = question.mid_gain_list
          self.mid_loss_list = question.mid_loss_list
          ...

class Welcome(object): #second window
      def __init__(self, master, csv_name_ses, csv_name_sub):
          self.master = master
          Welcome.csv_name_sub = str(self.entrySub.get())
          Welcome.csv_name_ses = str(self.entrySes.get())
          ...

class App1(Welcome, question): #third, last one appears
      def __init__(self, master, csv_name_ses, csv_name_sub, algorithmIndex, initX, mid_loss_list, mid_gain_list):
          super(App1, self).__init__(master, csv_name_ses, csv_name_sub, algorithmIndex, initX, mid_loss_list, mid_gain_list)
          ...    

def main():

   root = Tk()
   myApp = Welcome(root, csv_name_ses, csv_name_sub)
   root.mainloop()

Error msg:

super(App1, self).__init__(master, csv_name_ses, csv_name_sub, algorithmIndex, initX, mid_loss_list, mid_gain_list)
TypeError: __init__() takes 4 positional arguments but 8 were given

Solution

  • Your Welcome and question class are not written as cooperative superclasses. If you want to use super(..), you need to rewrite their __init__ method to accept any number of arguments, and they need to call super(..).__init__ again with all arguments that are not yet consumed.

    But for your situation it is probably easier to just explicitly call the superclass initializers:

    class Appl(Welcome, question):
        def __init__(self, master, csv_name_ses, csv_name_sub, algorithmIndex, initX, mid_loss_list, mid_gain_list):
            Welcome.__init__(self, master, csv_name_ses, csv_name_sub)
            question.__init__(self, algorithmIndex, initX, mid_loss_list, mid_gain_list)