[Python] Polymorphism in Python VS Polymorphism in JAVA

Discussão em 'Python' iniciado por Stack, Agosto 28, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to understand the polymorphism in python. Gone through lot of article but there is one doubt still there in my mind. When I compare with java it is little bit confusing for me in Python.

    As per my knowledge polymorphism is "one thing in many forms". Polymorphism can be demonstrated using operator overloading, and method overloading. Let's take method overloading as a means to demonstrate Polymorphism concept. In java we can write it without use of inheritance. See below code.

    public class Main{
    public static void main(String[] args) {
    System.out.println(add(1,2));;
    System.out.println(add(1,2,3));
    }
    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,3))


    The same method overloading works in java but not in python. Why there is difference?. If I want it to work then I have to change my python code as below:

    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 getting convinced that above the code is an example of Polymorphism. There are article like this not giving me convincing point.

    can anyone give me theory behind the polymorphism in python?

    Continue reading...

Compartilhe esta Página