39. Problem to create a single inheritance example in Python

In this Python oops program, we will create an single inheritance example in Python. Class called Manager that inherits from the Employee class.

Single inheritance example in Python

Steps to solve the program
  1. The Employee class is defined with a constructor method __init__ that takes name and salary as parameters and initializes the instance variables self.name and self.salary with the provided values.
  2. The class also has a method print_details that prints the employee’s name and salary.
  3. The Manager class is defined as a subclass of Employee class, inheriting its attributes and methods.
  4. The Manager class has an additional constructor method __init__ that takes name, salary, department, and bonus as parameters. It calls the superclass’s __init__ method using super() to initialize the name and salary attributes inherited from the Employee class, and initializes the department and bonus attributes with the provided values.
  5. The Manager class also has a method calculate_total_compensation that calculates the total compensation of the manager by adding their salary and bonus.
  6. The code creates an object manager of the Manager class by calling its constructor and passing the name “John Walker”, salary 60000, department “Sales”, and bonus 5000 as arguments.
  7. The calculate_total_compensation method is called on the manager object, which calculates the total compensation by adding the salary and bonus.
  8. The total compensation is then printed using the print statement.
  9. Thus, we have created a single inheritance example in Python.
				
					class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
    
    def print_details(self):
        print("Name:", self.name)
        print("Salary:", self.salary)

class Manager(Employee):
    def __init__(self, name, salary, department, bonus):
        super().__init__(name, salary)
        self.department = department
        self.bonus = bonus
    
    def calculate_total_compensation(self):
        total_compensation = self.salary + self.bonus
        return total_compensation

# Create an object of the Manager class
manager = Manager("John Walker", 60000, "Sales", 5000)
total_compensation = manager.calculate_total_compensation()
print("Total Compensation:", total_compensation)
				
			

Output:

				
					Total Compensation: 65000
				
			

Related Articles

Create a Python class called Employee with attributes name and salary.

Create a Python class called Customer with attributes name and balance.

Leave a Comment