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 | class Bear(object): |
Result:1
2Groarrr
Woof woof!
Abstract Class-Based Polymorphism
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 | class Document: |
Result:1
2
3Document1: 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
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 | class Car: |
Result:1
2
3Bananatruck: 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.
Leave a Reply:
The makeSound() method in the first example should not be indented.
Thanks for telling me! I have updated the post with the correct indetion. It should work fine now