Polymorphism in Python

Polymorphism for different classes having the same method names

class MarutiCar():
    def color(self):
        print("My Maruti Car Color is Blazing Red")
    def model(self):
        print("My Car Model is Swift Dzire")
    def pricing(self):
        print("My Car price in 2021 is 8,60,000")
class HondaCar():
    def color(self):
        print("My Honda Car Color is Blazing Red")
    def model(self):
        print("My Car Model is Honda Civic")
    def pricing(self):
        print("My Car price in 2021 is 21,00,000")
objMarutiCar = MarutiCar()
objHondaCar = HondaCar()
for cars in (objMarutiCar, objHondaCar):
    cars.color()
    cars.model()
    cars.pricing()  
My Maruti Car Color is Blazing Red
My Car Model is Swift Dzire
My Car price in 2021 is 8,60,000
My Honda Car Color is Blazing Red
My Car Model is Honda Civic
My Car price in 2021 is 21,00,000

Polymorphism with Inheretence

class Car():
    def color(self):
        print("My Car Color is Blazing Red")
    def model(self):
        print("My Car Model is Swift Dzire")
    def pricing(self):
        print("My Car price in 2021 is 8,00,000")

class KiaCar(Car):
    def model(self,a,b):
        self.a = a
        self.b = b
        print(a, b)
        print("My Kia Car Model is Seltos")
objKiaCar = KiaCar()
objKiaCar.model(10,20)

10 20
My Kia Car Model is Seltos

Polymorphism by passing Class Objects to Functions

def myFunc(obj):
    obj.color()
    obj.model()
    obj.pricing()

myFunc(objCar)
My Car Color is Blazing Red
My Car Model is Swift Dzire
My Car price in 2021 is 8,60,000

In-built and user defined Ploymorphism in Python

Learn more about Python Features in the upcoming blog articles.

Happy Learning!