python logo

Polymorphism


Python hosting: Host, run, and code Python in the cloud!

Polymorphism is a fundamental concept in object-oriented programming. This term refers to the ability of different classes to be treated as instances of the same class through inheritance. In Python, polymorphism is achieved in various ways, including with functions and abstract classes. This article delves into the concept, illustrating its practical implementation in Python.

The term ‘Polymorphism’ is derived from the Greek words ‘Poly’ (meaning many) and ‘morphism’ (meaning forms). Essentially, it enables us to leverage a single interface to represent different types.

Python Programming Bootcamp: Go from zero to hero

Function-Based Polymorphism in Python

Consider two distinct classes: Bear and Dog. Each of these classes has a method that produces a unique sound. Using polymorphism, we can invoke the respective sound method for any object of these classes through a common function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Bear(object):
def sound(self):
print("Groarrr")

class Dog(object):
def sound(self):
print("Woof woof!")

def makeSound(animalType):
animalType.sound()

bearObj = Bear()
dogObj = Dog()

makeSound(bearObj)
makeSound(dogObj)

Result:

1
2
Groarrr
Woof woof!

Abstract Class-Based Polymorphism

Polymorphism visual representation

When creating applications like a document editor, you may not know beforehand the types of documents a user will open, be it PDF or Word. Rather than having separate types for each document format, wouldn’t it be convenient to access them uniformly?

By defining an abstract class, we can outline a structure that every derived class must adhere to. Here’s how it works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Document:
def __init__(self, name):
self.name = name

def show(self):
raise NotImplementedError("Subclass must implement this abstract method")

class Pdf(Document):
def show(self):
return 'Show pdf contents!'

class Word(Document):
def show(self):
return 'Show word contents!'

documents = [Pdf('Document1'), Pdf('Document2'), Word('Document3')]

for document in documents:
print(document.name + ': ' + document.show())

Result:

1
2
3
Document1: Show pdf contents!
Document2: Show pdf contents!
Document3: Show word contents!

Through polymorphism, a single abstract entry point can be used to represent various types (like PDF and Word) following the same structure.

Python Programming Bootcamp: Go from zero to hero

Another Polymorphism Example

Another example visual representation

An abstract class, Car, could define methods like drive() and stop(). The implementations of these methods can then differ based on the specific type of car (like Sportscar or Truck).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Car:
def __init__(self, name):
self.name = name

def drive(self):
raise NotImplementedError("Subclass must implement this abstract method")

def stop(self):
raise NotImplementedError("Subclass must implement this abstract method")

class Sportscar(Car):
def drive(self):
return 'Sportscar driving!'

def stop(self):
return 'Sportscar braking!'

class Truck(Car):
def drive(self):
return 'Truck driving slowly because heavily loaded.'

def stop(self):
return 'Truck braking!'

cars = [Truck('Bananatruck'), Truck('Orangetruck'), Sportscar('Z3')]

for car in cars:
print(car.name + ': ' + car.drive())

Result:

1
2
3
Bananatruck: Truck driving slowly because heavily loaded.
Orangetruck: Truck driving slowly because heavily loaded.
Z3: Sportscar driving!

Through the power of polymorphism, we can abstract the specifics and use a unified approach to handle different types of cars.

Download Exercises

← Previous Topic | Next Topic →






Leave a Reply:




Irfan Sun, 4 Apr 2021

The makeSound() method in the first example should not be indented.

Frank Sun, 4 Apr 2021

Thanks for telling me! I have updated the post with the correct indetion. It should work fine now