Polymorphism In Python

With Python, I’m attempting to comprehend polymorphism. I’ve read several articles, but one question remains unanswered. As compared to Java, Python seems a little unclear for me.

Polymorphism, to the best of my understanding, is “one thing in numerous shapes.” Operator and method overloading can be used to show polymorphism. Let’s use method overloading to explain the Polymorphism idea. We can write it in Java without using inheritance. See the code below.

public class Main{
    public static void main(String[] args) {
        System.out.println(add(1,2));;
        System.out.println(add(1,2,));
    }
    public static int add(int a,int b){
        return a+b;
    }
    public static int add(int a,int b,int c){
        return a+b+c;
    }   
}

Python code:

class TestPolymorphism:
    def add(self,a,b):
        return (a+b)
    def add(self,a,b,c):
        return (a+b+c)

obj = TestPolymorphism()
print(obj.add(1,2)) #will get an error
print(obj.add(1,2,))

The same method overloading is possible in Java but not in Python. Why is there a distinction? If I want it to function, I must modify my Python code as follows:

class TestPolymorphism:
    def add(self,a,b,c=None):
        if c ==None:
            sum  = a+b
            return sum
        else:
            sum = a+b+c
            return sum

obj = TestPolymorphism()
print(obj.add(1,2))
print(obj.add(1,2,3))

I’m not certain that the code above is an example of polymorphism. There are articles like [link removed by moderator] that do not persuade me.

Can somebody clarify the philosophy underlying polymorphism in Python?

1 Like

There are a couple of quite different concepts here. The first is what’s actually called polymorphism, and that means that there are multiple types of things that all are, in some sense, the same type. That can be because they’re all subtypes of one thing (for instance, “natural person” and “legal person” are both subtypes of the broader type “person”, and thus can enter into contracts the exact same way), or because they both respond to the same protocol (for instance, dictionaries and lists, despite being very different, both respond to “what is your length?”, and so len(x) works just fine on both types).

What you’re looking at here, though, is function overloading. In a sense, this is the converse of polymorphism; instead of having one protocol that multiple things respond to, you have multiple protocols that the same thing (in this case, a function) responds to. In Python, we don’t usually need this, since there are other and much more flexible tools available (optional arguments, variadic functions, etc), but if you want to play around with it, look up functools.singledispatch which can do some of these sorts of things for you.

There are a few ways you could write your add() function. Here’s a sampling:

# Adding zero does nothing, so we can safely do this
def add(self, a, b, c=0):
    return a + b + c

# accept any number of parameters
def add(self, *numbers):
    total = 0
    for n in numbers:
        total += n
    return total

By the way, Python doesn’t require you to put everything into a class. You’re not actually using the class for anything here, so you may as well just have top-level functions and skip the self parameter. Java forces everything to go into classes because that’s how its bytecode is organized, but in Python, a module is a thing, and classes (if they’re used) exist inside modules.

7 Likes

Thank you so much for your help

1 Like

Or, you can just do

# Accept any number of numeric arguments
def add(self, *numbers):
    return sum(numbers)

(It should also be a staticmethod, but I don’t want to introduce too many tangential concepts here).

2 Likes

Well, yes, but that doesn’t really show anything off :slight_smile: Simple examples do often end up duplicating what already exists.

2 Likes

Yeah, that’s true…just didn’t want the OP to think they should re-invent the wheel, and also illustrate more of the simplicity and conciseness benefit of the varargs approach.

And by the way, @zainkhan , I just want to say that as a new user, we really appreciate the effort you’ve put into writing a well-written, detailed, focused and clear question particularly as a new user, providing appropriate minimal but complete examples and explaining what you’ve learned so far and what specifically you’d like to know about. That’s an important set of skills and one that will continue to benefit both yourself and others as you continue on your programming journey, and we encourage you to keep asking such. Best of luck!

3 Likes

Indeed, I will do so whenever I have a question, and thank you for your time.

2 Likes