0

I'm trying to create a daughter class that inherits from two parent classes, each of which has its own required inputs. However, when I try to initialize the daughter class I am getting an error that says it has the wrong number of inputs.

class A(object):
   def __init__(self, a=0, a1=0, a2=0):
      self.a = a
      self.a1 = a1
      self.a2 = a2

class B(object):
   def __init__(self, b=0, b1=0, b2=0):
      self.b = b
      self.b1 = b1
      self.b2 = b2

class C(A, B):
   def __init__(self, a, a1, a2, b, b1, b2):
      super().__init__(a, a1, a2, b, b1, b2)

but when I initialize C the following way:

c = C(a=1, a1=1, a2=1, b=2, b1=2, b2=2)

I get the error:

TypeError: A.__init__() takes from 1 to 4 positional arguments but 7 were given

What is the correct way to have multi class inheritance?

Adam
  • 107
  • 1
  • 7
  • Does this answer your question? [python multiple inheritance passing arguments to constructors using super](https://stackoverflow.com/questions/34884567/python-multiple-inheritance-passing-arguments-to-constructors-using-super) – matszwecja Aug 11 '23 at 14:15

2 Answers2

2

As pointed by the comment, it requires to adapt the base classes and it can become quite complicated as MRO (method resolution order) becomes involved to resolve the calls to super() (see python multiple inheritance passing arguments to constructors using super for more details)

However, it is ususally a strong code smell that you should not use inheritance but composition:

class C:
  def __init__(self, a, a1, a2, b, b1, b2):
    self.a_instance = A(a, a1, a2)
    self.b_instance = B(b, b1, b2)

Your class C can then act like a wrapper around the functionalities provided by the classes A and B

Coding thermodynamist
  • 1,340
  • 1
  • 10
  • 18
1

2 things here:

  • super() will follow the method resolution order meaning only A.__init__ is being called when you call super().__init__
  • you can still roughly accomplish what you need here using dictionary argument unpacking (after resolving the inheritance issue)
class A(object):
   def __init__(self, a=0, a1=0, a2=0):
      self.a = a
      self.a1 = a1
      self.a2 = a2
      print("a")

class B(object):
   def __init__(self, b=0, b1=0, b2=0):
      self.b = b
      self.b1 = b1
      self.b2 = b2
      print("b")

class C(A, B):
   def __init__(self, **kwargs):
      for klass in self.__class__.__mro__:
         super(klass, self).__init__(**kwargs)
Aaron
  • 10,133
  • 1
  • 24
  • 40