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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, but when I do if len(args)==1 I got the error "object of type bool has no lenght"
@Layla The definition of the function func, should have * before args. I am guessing you don't have that...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.