Inheritance and Polymorphism
Two of the most important pillars of Object-Oriented Programming (OOP) are Inheritance and Polymorphism. These concepts allow you to massively reduce code repetition and create flexible systems.
Inheritance
Inheritance allows creating a new class (Child Class / Subclass) that absorbs all the attributes and methods of an existing class (Parent Class / Superclass), and can also add its own or modify the inherited ones.
Imagine you have different types of employees. They all have a name and salary, but different tasks.
# PARENT CLASS
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def work(self):
print(f"{self.name} is performing generic duties for a salary of {self.salary}.")
# CHILD CLASS (Inherits from Employee)
class Developer(Employee):
def __init__(self, name, salary, favorite_language):
# super() calls the constructor of the Parent class
super().__init__(name, salary)
self.favorite_language = favorite_language
# "Overriding" a method
def work(self):
print(f"{self.name} is writing code in {self.favorite_language}.")
class Manager(Employee):
def work(self):
print(f"{self.name} is managing the team.")
When using it:
john = Developer("John", 4000, "Python")
anna = Manager("Anna", 6000)
john.work() # Output: John is writing code in Python.
anna.work() # Output: Anna is managing the team.
Polymorphism
Polymorphism means "many forms". In programming, it allows objects of different classes (usually related by inheritance) to respond differently to exactly the same method name.
In the previous example, both john and anna can execute the .work() method, but the behavior will be different depending on the "type" of object they are (Developer vs Manager).
Why is Polymorphism useful?
Imagine you have a mixed list of many different types of employees and you need them all to start working at 9 AM. You don't need to check what each one is, you just call their method.
# List of objects of different types, but with a common method
team = [
Developer("Carlos", 3000, "JavaScript"),
Manager("Maria", 5000),
Employee("Peter", 2000)
]
for member in team:
# Polymorphism in action: each object knows HOW to work its own way.
member.work()
These two concepts combined make structuring large applications and maintaining them over time infinitely easier.