Course Content
In-Depth Python OOP
4. Polymorphism and Abstraction
In-Depth Python OOP
What is Polymorphism?
Polymorphism is one of the fundamental concepts in object-oriented programming (OOP). It refers to the ability of different classes to share the same attributes and methods while exhibiting different behaviors.
Let's consider an example of polymorphism:
The len()
function exhibits different behaviors depending on the type of data it operates on. This example serves as a demonstration of polymorphism in action.
Polymorphism Implementation
To implement polymorphism, we can create classes that share the same attributes and methods:
Code Description
In the provided Python code, polymorphism is demonstrated through the usage of the
Each class provides its own implementation of the
During the loop iteration, instances of
The
info
method in different classes: User
, Admin
, and Hacker
.Each class provides its own implementation of the
info
method specific to its role. The method takes a parameter some_value
, and the behavior of the info
method varies based on the class it belongs to. This ability of different classes to provide their own implementations of the same method is what constitutes polymorphism.During the loop iteration, instances of
User
, Admin
, and Hacker
are stored in the list lst
. When the loop is executed, it accesses the info
method for each item in the list. The method executed for each item is based on the class it belongs to, resulting in different outputs for each role.The
User
class prints "This is standard user." followed by some_value + 100
. The Admin
class prints "This is admin of this service." followed by some_value * 100
. The Hacker
class prints "This person can thief your data." followed by some_value * 0
. This demonstrates how polymorphism allows us to treat different objects uniformly and call the same method on them, while their specific implementations are executed based on their individual class definitions.
Note
Polymorphism in Python refers to the ability of objects to exhibit different behaviors while performing the same actions.
Everything was clear?
Section 4. Chapter 1