-1

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

  • 1
    Does this answer your question? [Calling parent class \_\_init\_\_ with multiple inheritance, what's the right way?](https://stackoverflow.com/questions/9575409/calling-parent-class-init-with-multiple-inheritance-whats-the-right-way) – ljmc Dec 27 '22 at 18:33

1 Answers1

0

*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')
Wolric
  • 701
  • 1
  • 2
  • 18