Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inheriting more than 1 parent class in python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading