Inheritance Case Study
This case study brings together everything covered in this module - classes, constructors, inheritance, method overriding, and getters/setters - into a single, realistic example: modeling employees at a company.
The Scenario
A company wants to model two types of employees: a general Employee and a more specific Manager, who is also an employee but has an additional responsibility - managing a team - and a different way of calculating their bonus.
class Employee:
def __init__(self, name, salary):
self.name = name
self.__salary = salary # private attribute
@property
def salary(self):
return self.__salary
@salary.setter
def salary(self, amount):
if amount < 0:
print("Salary cannot be negative")
else:
self.__salary = amount
def calculate_bonus(self):
return self.__salary * 0.05
def details(self):
print(f"{self.name} earns a bonus of {self.calculate_bonus()}")
class Manager(Employee):
def __init__(self, name, salary, team_size):
super().__init__(name, salary)
self.team_size = team_size
def calculate_bonus(self): # overriding
base_bonus = super().calculate_bonus()
return base_bonus + (self.team_size * 500)
def details(self): # overriding
super().details()
print(f"{self.name} manages a team of {self.team_size}")
Putting It All Together
emp = Employee("Rohit", 50000)
mgr = Manager("Priya", 80000, 6)
emp.details()
# Rohit earns a bonus of 2500.0
mgr.details()
# Priya earns a bonus of 43000.0
# Priya manages a team of 6
Notice how Manager reuses Employee's constructor and salary logic through super(), but overrides calculate_bonus() and details() to add its own specific behavior - a clean, realistic demonstration of inheritance, overriding, and encapsulation working together.
Coming Up Next
Next, the course moves into Python's module system, starting with the Standard Library - the vast collection of built-in modules that ship with Python.