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
Employeewith an__init__that storesnameandbase_salary. - Add a
calculate_pay()method toEmployeethat returnsbase_salary. - Add a
__str__method toEmployeethat returns a string likeEmployee: Alice | Pay: $3000. - Define a subclass
Managerthat inherits fromEmployee. Manager.__init__should accept an additionalbonusparameter and callsuper()to initialise the parent.- Override
calculate_pay()inManagerto returnbase_salary + bonus. - Override
__str__inManagerto return a string likeManager: Bob | Pay: $5500. - Create one
Employeeand oneManagerinstance 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.
- Polymorphism —
print(emp)andprint(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 useprint()orstr()on an object.
Test Console
Run code to see output...