0

In Java I was able to make method overloading inside a class like the following (pseudocode):

public class Test
private double result;

Test(){result=0;}

public double func(int a, int b, int c)
{
    result=a+b+c;
}

public double func(int a, int b)
{
    result=a*b;
}

public double func(int a)
{
    result=Math.pow(a,2);
}

How can I get the same behaviour in Python? I know that I can use default values, but I got a problem when I want to implement different operations in a method.

Any help?

Layla
  • 5,234
  • 15
  • 51
  • 66

1 Answers1

1

You can do this with a same function, but with number of arguments you can decide what action you want to carry out, like this

class Test:
    def func(*args):
        if len(args) == 1:
           return args[0] * args[0]
        elif len(args) == 2:
            return args[1] * args[0]
        elif len(args) == 3:
            return sum(args)
        else:
            raise "Unexpected number of arguments"

In Python, when you define a class with more than one function with the same name, the last function will overwrite the definitions of the previous functions with the same name, because the function and class association happens very late.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • thanks, but when I do if len(args)==1 I got the error "object of type bool has no lenght" – Layla Sep 30 '14 at 14:31
  • 1
    @Layla The definition of the function `func`, should have `*` before `args`. I am guessing you don't have that... – thefourtheye Sep 30 '14 at 14:31