0
class Base1:
   def  __init__(self,a):
         self.a=a
   def  addition(self):
         return self.a + self.a
class Base2:
   def  __init__(self,b):
         self.b=b
   def  multipl(self):      
        return self.b*self.b
class Sub(Base1,Base2):
   def  __init__(self,a,b):
       super().__init__(a,b)


H=Sub(4,5)
print(H.addition())
print(H.multipl())

TypeError: init () takes 2 positional arguments but 3 were given

Well, when I do it like this, what I expected happens, why? What does "* args" do to avoid that error?

class Base1:
   def  __init__(self,a,*args):
         super().__init__(*args)
         self.a=a
         
   def  addition(self):
         return self.a + self.a
class Base2:
   def  __init__(self,b,*args):
         super().__init__(*args)
         self.b=b
         
   def  multipl(self):      
        return self.b*self.b
class Sub(Base1,Base2):
   def  __init__(self,a,b):
       super().__init__(a,b)


H=Sub(4,5)
print(H.addition())
print(H.multipl())

jose rosales
  • 335
  • 2
  • 6
  • https://stackoverflow.com/questions/3394835/use-of-args-and-kwargs Check out this answer. Might help you :) – jda5 Mar 23 '21 at 22:55

2 Answers2

0

In the dysfunctional first program it seems you expect that Sub.__init__'s super().__init__(a,b) would call both Base1's and Base2's __init__ and magically distribute a to the former and b to the latter - but that isn't so; actually only Base1.__init__ is called with the implicit self and the two further arguments a and b, making those three about which the error message rightly complains __init__ () takes 2 positional arguments but 3 were given.
The change in Base1 to def __init__(self,a,*args): catches the third argument b in *args so that there's no longer a surplus argument; you could as well def __init__(self, a, b):.

Armali
  • 18,255
  • 14
  • 57
  • 171
0

lemme explain to you the basic purpose of using *args in any function, I hope it may help you in understanding the purpose of *args in your function:

let a function:

    def total(a,b):
        return a+b
    print(total(1,2,3,4))

it will give you the error as follows:

Traceback (most recent call last):
  File "stack.py", line 3, in <module>
    print(total(1,2,3,4))
TypeError: total() takes 2 positional arguments but 4 were given

its because we have defined two parameters in function 'total' but passed 4 arguments while calling a function, and remember we cannot pass more than two arguments, So to resolve this issue, we use *args which says that n number of arguments will be passed in function. The same function using *args is as follows:

def all_total(*args):
    total = 0
    for i in args:
        total+=i
    return total
print(all_total(1,2,3,4,5,5))

It will give 20 as output. it shows that now we can pass any no. of arguments we want in any function without any error, this is the magic of *args. Same is the case with init function in your case.

I hope it helped you and welcome to python :)