DEV Community

datatoinfinity
datatoinfinity

Posted on • Edited on

Polymorphism

Polymorphism derived from greek words "Poly" (many) and morph("form"), refers to the ability of a single function, method, operator, or object to take on different forms or behaviours depending on the context.

It just like a person with different attitude in front of you confident to the family maybe cranky.

class Car:
    def __init__(self,brand,model):
        self.brand=brand
        self.__model=model
        
    def get_brand(self):
        return self.__model+"!"
    def full_name(self):
        return f"{self.brand} {self.__model}"
    def fuel_type(self):
        return "Petrol Diesel"
        
class ElectricCar(Car):
    def __init__(self,brand,model,battery_size):
        super().__init__(brand,model)
        self.battery_size=battery_size
    def fuel_type(self):
        return "Electric Charge"
        
my_safari=Car("TATA","sedan")
my_tesla=ElectricCar("Tesla","X-series","80kwh")
print(my_safari.fuel_type())
print(my_tesla.fuel_type())
Output:
Petrol Diesel
Electric Charge
  1. As you can see we have used same function fuel_type with different value.
  2. fuel_type function in class Car and fuel_type function in Electric Car class.

Top comments (0)