Python Object-Oriented Programming: Polymorphism

# Parent Class
class Shape:
def __init__(self):
self.sides = 0
def getArea(self):
class Rectangle(Shape):
def __init__(self, width=0, height=0):
self.width = width
self.height = height
self.sides = 1
def getArea(self):
return (self.width * self.height)
class Circle(Shape):
def __init__(self, radius=0):
self.radius = radius
def getArea(self):
return (self.radius * self.radius * 3.14)

Duck Typing

It is one of the most useful concepts in Python Object-Oriented Programming. We can implement polymorphism without using inheritance by using duck typing.

x = 5 # type of x is an integer
print (type(x))
x = "Medium" # type x is now string
print (type(x))
class Dog:
def Speak(self):
print("Woof Woof")
class Cat:
def Speak(self):
print("Meow meow")
class AnimalSound:
def Sound(self, animal):

Abstract Base Classes

Duck typing is useful as it simplifies the code and the user can implement the functions without worrying about the data type.


To define an abstract base class, we use the abc module. The abstract base class is inherited from the built-in ABC class. We have to use the decorator @abstractmethod above the method that we want to declare as an abstract method.

from abc import ABC, abstractmethodclass ParentClass(ABC):

def method(self)



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store