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?
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