Python

Polymorphism

A seemingly difficult concept dealing with method overriding

What is polymorphism?

Polymorphism just means the ‘ability to take on various forms.’ In Python, the whole deal about this concept is that it lets us define methods in a child class with the same name as that in the parent class. Essentially, it allows us to edit parent class methods in the child class. This is known as method overriding.

Let’s work with an example:

class Animal: 
    def make_noise(self):
        print("I can make noise!")
class Dog(Animal):
    def make_noise(self):
        super().make_noise()
        print("ruff ruff")
    
some_animal = Animal()
some_animal.make_noise()

dog = Dog()
dog.make_noise()

Output:

I can make noise!
I can make noise!
ruff ruff

Here, the ‘some_animal’ object is of the ‘Animal’ class which has a simple ‘make_noise()’ method. When called, this method prints out ‘I can make noise!.’ Now, we create a ‘Dog’ class that inherits the ‘Animal’ class. It overrides the ‘make_noise()’ method by building on the existing method. It uses ‘super().make_noise()’ to access the parent class ‘make_noise()’ method. Then it builds on it by also saying "ruff ruff". That’s the whole idea behind polymorphism and method overriding in Python.

chevron_up