Home > Software engineering >  Inheriting more than 1 parent class in python
Inheriting more than 1 parent class in python

Time:12-28

I am trying to inherit 2 classes as parent class in a child class both have different class variables class A has a,b while class B has c,d,e they are the parent to class AB(A,B) now i want to make an object of AB class but i am not able understand how to pass the value while i try to create an object of AB class

class A:
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def testa(self):
        print('inside A')
class B:
    def __init__(self,c,d,e):
        self.c = c
        self.d = d
        self.e = e
    def testb(self):
        print('inside B')

class AB(A,B):
    def __init__(self,*args):
        A.__init__(self,*args)
        B.__init__(self,*args)

obj = AB(1,2,3) # this is throwing error

CodePudding user response:

This is happening because you are calling the __init__ method of the A and B classes with the *args argument, which is causing all the arguments to be passed as a single tuple. This is happening because you are calling the __init__ method of the A and B classes with the *args argument, which is causing all the arguments to be passed as a single tuple. To fix this, you can define the __init__ method in the AB class and accept the values for the variables as separate arguments, like this:

class AB(A,B):
    def __init__(self, a, b, c, d, e):
        A.__init__(self, a, b)
        B.__init__(self, c, d, e)

now you can pass the values like this:

obj = AB(1, 2, 3, 4, 5)

CodePudding user response:

*args will always unpack all values. And as A only expects 2 values it throws an error, when you pass 3 values. To limit args to 2 elements use slicing [:2] if you want to pass the first 2 elements to A

So your AB's init should look like this:

class AB(A,B):
    def __init__(self, *args):
        A.__init__(self, *args[:2])
        B.__init__(self, *args)

Additionally, you'll run into an error with your methods testa and testb as they are missing self which is always passed to methods of an instance.

Just add self to both methods to avoid a TypeError

def testa(self):
        print('inside A')
  • Related