What is Polymorphism and types of Polymorphism in Python oops?

The term polymorphism is derived from two Greek words:

  1. "Poly-": Meaning "many" or "multiple."
  2. "Morphism": Meaning "form" or "shape."

Thus, polymorphism essentially means "many forms." In the context of programming and computer science, it refers to the ability of different objects or functions to be treated as instances of the same type or to take on many forms, enabling flexibility and reusability in code.

 

Types of Polymorphism

  1. Compile-time Polymorphism (Static Polymorphism)
  2. Run-time Polymorphism (Dynamic Polymorphism)

1) Compile-time Polymorphism:

The method to be executed is determined at compile time.

Types of Compile-time Polymorphism:

  1. operator overloading
  2. method overloading

2) Run-time Polymorphism:

The method to be executed is determined at runtime, allowing for dynamic behavior.

Types of Run-time Polymorphism:

  1. method overriding

 

Operator overloading in Python oops:

Firstly you have to understand what are operators:

operator and operands

In python, every operator (+, -, /, *, =, %, ...) have there pre define functionality. it means when you are usng + this symbal then in the background of this symbol a function is call thats is __add__. For every symbol thier is a function with their functionality.
So, Operator overloading is a  concept where we are able to modify the functionlity of the existing or pre buit function within a class.

For Example:

In python, every operator (+, -, /, *, =, %, ...) have there pre define functionality. it means when you are using + this symbol then in the background of this symbol a function is called that is __add__. For every symbol, there is a function with their functionality.
So, Operator overloading is a concept where we are able to modify the functionality of the existing or pre-built function within a class.

We have a + symbol, the functionality of this symbol is to take two types of operands and add them. 
Let's change the functionality of the symbol of +. I want to make it like, if i do 300 + 200 then the output will be 100.
Let's do it:

class ModifySymbol:
    def __init__(self, a, b):
        self.x = a
        self.y = b
    
    def __add__(self, other):
        first_values = self.x - other.x
        second_values = self.y - other.y
        obj = ModifySymbol(first_values, second_values)
        return obj

obj_x = ModifySymbol(200, 500)
obj_y = ModifySymbol(50, 100)

solve = obj_x + obj_y

print(solve.x)
print(solve.y)

Output:

150
400

In the given example, now when I use the + operator to add these two veriables then the override method is run.

it works like this:

200 + 50 = 150

500 + 100 = 400


 

Method overloading in Python oops:

Note : Method overloading is not supported in Python.

Method overloading defines, when we have multiple methods with the same name,  in a single class, Then which one method is executed when we call a method completely depends on how many parameters we pass in the method.

For Example:

class myClass:
    def sumthis(self, a, b, c):
        summ = a + b + c
        print(summ)
    
    def sumthis(self, a, b):
        summ = a + b
        print(summ)
    
    def sumthis(self, a):
        summ = a
        print(summ)

obj = myClass()
obj.sumthis(12, 10)

According to this example or definition of method overloading, the second method has to execute, but Python is not supporting this. By default Python focuses on the method we create at the end.

But we achieve this functionality by applying some logic:

class myClass:
    def sumthis(self, a = None, b = None, c = None):
        if a != None and b != None and c != None:
            summ = a + b + c
            print(summ)
    
        elif a != None and b != None:
            summ = a + b 
            print(summ)
        
        elif a != None:
            summ = a
            print(summ)

obj = myClass()
obj.sumthis(12, 10)

Output:

22

 

Method overriding in Python oops:

When we have a relationship between parent and child class. Or we create a method in the parent class with their functionality and with the same name we create a method in the child class with another function. Now if we create an object of child class or call that method which has same name, then the child class method is executed not parent class method.

Example:

class myCls:
    def car(self):
        print("this is a car.")
    
    def bus(self):
        print("this is a bus.")

class myChildCls(myCls):
    def car(self):
        print("this is not a car.")

obj = myChildCls()
obj.car()
obj.bus()

Output:

this is not a car.
this is a bus.

 


 

Python OOPs Polymorphism: 20 Interview Questions with Answers and Examples.

Question 1. What is polymorphism in Python?

Answer: Polymorphism in Python is an OOP concept that allows objects of different classes to be treated as objects of a common superclass. It enables a single interface to represent different underlying forms (data types). For example, different classes might implement the same method, but with different behaviors.

Example:

class Dog:
    def sound(self):
        return "Woof!"

class Cat:
    def sound(self):
        return "Meow!"

def make_sound(animal):
    print(animal.sound())

make_sound(Dog())
make_sound(Cat())

Output:

Woof!
Meow!

 

 Question 2. What are the types of polymorphism in Python?

Answer: The two main types of polymorphism in Python are:

  1. Compile-time polymorphism (Static Polymorphism): Achieved using method or operator overloading.
  2. Run-time polymorphism (Dynamic Polymorphism): Achieved using method overriding.

 

Question 3. What is method overloading in Python, and is it supported?

Answer: Method overloading allows multiple methods with the same name but different parameters within the same class. Python does not natively support method overloading. The latest defined method overrides any previous methods with the same name.

Example:

class MyClass:
    def display(self, a=None, b=None):
        if a and b:
            print(a + b)
        elif a:
            print(a)
        else:
            print("No arguments")

obj = MyClass()
obj.display(5, 10)  
obj.display(5) 

Output:

15
5

 

Question 4. What is operator overloading?

Answer: Operator overloading allows custom behavior for operators (e.g., +, -) when applied to objects of a user-defined class by redefining their special methods.

Example:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

p1 = Point(2, 3)
p2 = Point(4, 1)
result = p1 + p2
print(result.x, result.y) 

Output:

6 4

 

Question 5. How is method overriding used in Python?

Answer: Method overriding allows a child class to provide a specific implementation of a method that is already defined in its superclass.

Example:

class Animal:
    def sound(self):
        return "Some sound"

class Dog(Animal):
    def sound(self):
        return "Woof!"

dog = Dog()
print(dog.sound())  

Output:

Woof!

 

Question 6. How does Python support polymorphism with functions?

Answer: Python supports polymorphism by allowing functions to accept any object that has the required attributes or methods, regardless of the object's class.

Example:

class Dog:
    def sound(self):
        return "Woof!"

class Cat:
    def sound(self):
        return "Meow!"

def make_sound(animal):
    print(animal.sound())

make_sound(Dog())  
make_sound(Cat())  

Output:

Woof!
Meow!

 

Question 7. Can you achieve polymorphism with inheritance?

Answer: Yes, polymorphism can be achieved with inheritance by overriding methods in child classes.

Example:

class Animal:
    def move(self):
        return "Moving"

class Fish(Animal):
    def move(self):
        return "Swimming"

fish = Fish()
print(fish.move()) 

Output:

Swimming

 

Question 8.  What is dynamic method resolution?

Answer: Dynamic method resolution refers to how Python decides which method to execute at runtime, depending on the type of object.

 

Question 9.  Can polymorphism be achieved without inheritance?

Answer: Yes, polymorphism can be achieved without inheritance in Python, using duck typing.

 

Question 10.  What is the purpose of __str__ method in Python?

Answer: The __str__ method provides a human-readable string representation of an object when print is used.

Example:

class Person:
    def __str__(self):
        return "Person object"

print(Person()) 

Output:

Person object

 

Question 11.  Can you overload the equality operator?

Answer: Yes, by defining the __eq__ method, we can overload the equality operator.

Example:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

p1 = Point(1, 2)
p2 = Point(1, 2)
print(p1 == p2)

Output:

True

 

Question 12. What is polymorphism with abstract classes?

Answer: Abstract classes use polymorphism by defining abstract methods that child classes must implement.

 

Question 13.  How does polymorphism benefit code reuse?

Answer: Polymorphism allows generic code to handle multiple types, making code more flexible and reusable.

 

Question 14.  Can built-in Python types be polymorphic?

Answer: Yes, built-in types like lists and strings exhibit polymorphic behavior through methods like __add__.

 

Question 15.  What is isinstance in polymorphism?

Answer: isinstance checks if an object is an instance of a class, which is useful for enforcing polymorphic behavior.

 

Question 16. How do you implement polymorphism with interfaces?

Answer: In Python, interfaces can be simulated using abstract classes with abstract methods.

 

Question 17.  What is the role of the __call__ method in polymorphism?

Answer: The __call__ method allows objects to be called like functions, enabling callable polymorphic objects.

 

Question 18. How can polymorphism improve maintainability?

Answer: Polymorphism reduces the need for type-specific code, making programs easier to modify and extend.

 

Question 19. Can you give an example of polymorphism in a real-world application?

Answer: In a drawing application, different shapes can have a common draw method, allowing the same interface for various shapes like circles, squares, and triangles.

 

Question 20. What is duck typing?

Answer: Duck typing is a form of polymorphism where an object's suitability is determined by the presence of certain methods and properties rather than the object's type.

Example:

class Bird:
    def fly(self):
        return "Flying"

class Plane:
    def fly(self):
        return "Taking off"

def take_off(entity):
    print(entity.fly())

take_off(Bird())  
take_off(Plane())

Output:

Flying
Taking off

 

Leave a comment

You must be logged in to post a comment.

0 Comments