Python Polymorphism


What is Polymorphism?

Polymorphism actually means multiple forms. It means methods or functions with the same name can be used for different operations.

Built-in functions Polymorphism

The len() function is the great example for built-in functions polymorphism. If we supply the string type of data, then it returns a count of the number of characters in the string and if we supply any other data type like list, tuple, etc, then it returns a count of items.

In [1]:
print(len("Logical"))
print(len(["Logical", "Python"]))
7
2

Class Polymorphism

Polymorphism helps us to have multiple classes to have methods with the same name.

In [1]:
class petrol_Car:
    def __init__(self, petrol_Capacity):
        self.petrol_Capacity = petrol_Capacity
    
    def car_details(self):
        print("This is a petrol car with petrol capacity of:",self.petrol_Capacity)
        
class diesel_Car:
    def __init__(self, diesel_Capacity):
        self.diesel_Capacity = diesel_Capacity
    
    def car_details(self):
        print("This is a diesel car with diesel capacity of:", self.diesel_Capacity)

civic = petrol_Car(35)
corolla = diesel_Car(40)

for car in(civic, corolla):
    car.car_details()
This is a petrol car with petrol capacity of: 35
This is a diesel car with diesel capacity of: 40

Polymorphism and Inheritance

In inheritance, polymorphism allows us to re-implement the method of the base class in the child class. In this case, for the object of the child class, it will call the method of the child class and for the object of the base class, it will call the object of the base class.

In [1]:
class Car:
    def __init__(self, seating_capacity):
        self.seating_capacity = seating_capacity

    def car_details(self):
        print("This is a car.")

class Electric_Car(Car):
    def __init__(self, seating_capacity, cartype):
        Car.__init__(self, seating_capacity)
        self.cartype = cartype

    def car_details(self):
        print("This is an electric car.")
        
mustang = Car(2)
model_3 = Electric_Car(2, "Electric")

mustang.car_details()
model_3.car_details()
This is a car.
This is an electric car.