Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Polymorphism in Python

Last Updated on January 30, 2023 by Sumit Kumar

In this article, we will discuss polymorphism, polymorphism in python, polymorphism with class methods , polymorphism with inheritance, and polymorphism with a function and objects.

What is Polymorphism?

Two terms, "poly" and "morphs," make up the term polymorphism. Poly denotes numerous, whereas morph refers to the shape. We comprehend polymorphism as the ability to complete a task in various ways.
Polymorphism refers to the existence of various forms. Polymorphism in programming refers to the usage of the same function name (but various signatures) for several kinds. The data types and quantity of arguments utilized in the function are the main differences

Code Implementation:

# your code goes here
# your code goes here


#program to understand polymorphism
 
# len() here this len() function use for string length
print(len("Prepbytes"))
 
# len() and here it use for list
print(len([1, 2, 3]))

Output:

9
3

Explanation : In the above python program we use len() function for calculating the length of string (“Prepbytes”) which of 9 length and we also use len() function for calculating the length of list
Which is of 3 lengths So this polymorphism.

Polymorphism with Class Methods:

Python can use two different class types in the same way, as demonstrated by the code below,a for loop that iterates over a tuple of objects is made. After that, call the methods without concern about what class type each object belongs to. We presume that each class truly contains these methods.

Code Implementation:

class A():
    
    def name(self):  
        print("My name is A")  
    
    def place(self):  
        print("MUMBAI") 
    
    
  
  
class B():  
    def name(self):  
        print("My name is B")  
  
    def place(self):  
        print("DELHI")  
   
  
obj1 = A()  
obj2 = B()  
for x in (obj1, obj2): 
    
    x.name()
    x.place()
    # your code goes here

Output:

My name is A
MUMBAI
My name is B
DELHI

Explanation:
In the above python program we create two classes A and class B and they have two methods – ‘name’ and ‘place’. The ‘name’ function simply prints the (“my name is A”)for class A and prints
(“my name is B”) for class B . after that we create two objects one is obj1 of class A and the other is obj2 of class B. Now in code ‘for’ loop iterates on both tuples of objects and use their methods to assume that these methods actually exist in each class.

Polymorphism with Inheritance:

In Python, polymorphism enables us to define child class methods with the same names as parent class methods. The parent class’s methods are passed down to the child class through inheritance. A method that a child class has inherited from its parent class, however, may be changed. This is especially helpful when the method that the child class inherited from the parent class doesn’t fully fit that class. In certain circumstances, the method is re-implemented in the child class. Method overriding is the practice of re-implementing a method in the child class.

Code Implementation:

# your code goes here

class Birds:  
    def intro(self):  
        print("i am bird.")  
    def flight(self):  
        print("birds may fly or may not fly")  
  
class sparrow1(Birds):  
    def flight(self):  
        print("Sparrows  can fly.")  
      
class ostrich1(Birds):  
    def flight(self):  
        print("Ostriches cannot fly.")  
      
obj_birds = Birds()  
bird1 = sparrow1()  
bird2 = ostrich1()  
  
obj_birds.intro()  
obj_birds.flight()  
  
bird1.intro()  
bird1.flight()  
  
bird2.intro()  
bird2.flight()

Output:

i am bird.
birds may fly or may not fly
i am bird.
Sparrows  can fly.
i am bird.
Ostriches cannot fly.

Polymorphism with a Function and Object

We can also create functions that can take any object, This allows for polymorphism. In the context of a function, polymorphism allows a function to be called with objects of different types and for the function to behave differently depending on the type of the object passed to it.
For example, a function that takes an object as an argument and prints its properties might print the properties of a dog differently than the properties of a cat, even though both are passed to the same function.

Code Implementation:

# your code goes here
# your code goes here

class A():
    
    
    
    def place(self):  
      print(" I am A - Agra")  
    
    def capital(self):     
      print("No i am not capital")  
  
     
  
class B(): 
    
    def  place(self):  
      print("I am B from Banglore")  
    
    def capital(self):  
      print(" yes i am capital")  
  
     
 
def func(obj): 
    
    obj.place()  
    obj.capital()  
      
  
obj1 = A()  
obj2 = B()  

func(obj1)  
func(obj2)

Output:

I am A - Agra
No i am not capital
I am B from Banglore
 yes i am capital

Explanation:
In the above python program we have a function that takes an object as an argument, we make two classes, class A and class B and both this class have two methods name as ‘place’ and ‘capital’.
Here obj1 is an object of class A and similarly, obj2 is of class B . we have a function name func which takes this object as an argument,In ‘func’ function we use class methods (‘place’, capital’)
So Even though we use the name "obj", any object that is instantiated will be able to call into this function.

Summary
As a result, polymorphism simplifies and improves the readability of the code. It also decreases the reading difficulty and saves many lines of code. Polymorphism is a very helpful notion in object-oriented programming that can also be used in real-world circumstances. Real World and Polymorphism are, after all, great friends

In Python polymorphism can be achieved using inheritance and overriding methods. A base class can define a method with certain behavior, and child classes can override that method to provide their own behavior. When an object of the child class is passed to a function that expects an object of the base class, the behavior of the function will be determined by the overridden method in the child class.

Leave a Reply

Your email address will not be published. Required fields are marked *