Overloading, overriding vs *args

Is there a simple way to use class overloading and/or overriding functionality to make this snippet work without the use of *args?

class Calc1: def multiply(self,a,b): print(a*b) class Calc2(Calc1): def multiply(self,a,b,c): print(a*b*c) super().multiply() oper_01 = Calc2() oper_01.multiply(5,10)

What’s the end goal here? Is Calc2.multiply supposed to get the product of a, b and c? How does the two argument/binary method Calc1.multiply relate to the (three or an arbitrary number?) arguments in Calc2.multiply?

Do you know how many arguments there are in the first place though? Without knowing how many arguments there are beforehand then perhaps you could pass a container/iterable as the argument instead of passing multiple arguments and simply rely on a loop, code folding e.g. reduce or otherwise to perform the operation (sidestepping *args but I’m not 100% what you’re really after).

My goal with this piece of code is to make Calc2 work with either two or three variables, performing multiplication with two variables by inheriting from another class. I was trying to achieve this by using the properties of classes.

If you want exactly three arguments then you’re probably right to try and avoid *args if possible. However you might have problems with trying to use print instead of return, since one call would rely on the other you may as well write an entirely new method otherwise.

If it returned then you could use the result of the first call with a, b as the first argument of another call with c. If not perhaps you could simply introduce a default value to c. Then you can pass 2 or 3 variables as preferred.

I assume the idea is to do something like this:

def mult2( a, b):
  return a * b

def mult3( a, b, c):
  return mult2( mult2(a,b), c)

To accomplish that, notice Calc2 class’s multiply function requires arguments (it needs 2 other than self) when its called


should be at least

super().multiply(a, b)

[ because there has to be an a and b for def multiply(self,a,b): from the Calc1 class ]

but you need to do something more complicated (see the code earlier in this post)
(and this line might also need return, as suggested in the previous post)

Here’s a non-class version that might be useful to consider:

def multiply( a, b, c = None):
  if c is None:
    return a * b * c
    return a * b

or this:

def mult( a, b = 1, c = 1): 
   return a * b * c