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?