← Previous Module 9: Inheritance & Polymorphism Next →
Statement
Solution

Python Exercise 9.1: Employee System

Inheritance lets a child class reuse and extend the behaviour of a parent class. Build an Employee base class and a Manager subclass that overrides the pay calculation to include a bonus.

Your program should:

  • Define a base class Employee with an __init__ that stores name and base_salary.
  • Add a calculate_pay() method to Employee that returns base_salary.
  • Add a __str__ method to Employee that returns a string like Employee: Alice | Pay: $3000.
  • Define a subclass Manager that inherits from Employee.
  • Manager.__init__ should accept an additional bonus parameter and call super() to initialise the parent.
  • Override calculate_pay() in Manager to return base_salary + bonus.
  • Override __str__ in Manager to return a string like Manager: Bob | Pay: $5500.
  • Create one Employee and one Manager instance and print both.

Sample Interaction:

Input
Output
(None)
Employee: Alice | Pay: $3000 Manager: Bob | Pay: $5500

Solution

Manager inherits everything from Employee and only overrides the methods that differ, keeping the code clean and DRY.

class Employee: def __init__(self, name, base_salary): self.name = name self.base_salary = base_salary def calculate_pay(self): return self.base_salary def __str__(self): return f"Employee: {self.name} | Pay: ${self.calculate_pay()}" class Manager(Employee): def __init__(self, name, base_salary, bonus): super().__init__(name, base_salary) self.bonus = bonus def calculate_pay(self): return self.base_salary + self.bonus def __str__(self): return f"Manager: {self.name} | Pay: ${self.calculate_pay()}" # Create instances emp = Employee("Alice", 3000) mgr = Manager("Bob", 4000, 1500) print(emp) print(mgr)

Key Concepts:

  • class Child(Parent): syntax creates a subclass that inherits all parent attributes and methods.
  • super().__init__(...) calls the parent constructor, avoiding code duplication.
  • Method overriding — defining a method in the child with the same name replaces the parent's version.
  • Polymorphismprint(emp) and print(mgr) call the same __str__ name but produce different results based on the object's actual type.
  • __str__ is a dunder (magic) method Python calls automatically when you use print() or str() on an object.
Python 3
Test Console
Run code to see output...

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top