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
- 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.
- The class also has a method print_details that prints the employee’s name and salary.
- The Manager class is defined as a subclass of Employee class, inheriting its attributes and methods.
- 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.
- The Manager class also has a method calculate_total_compensation that calculates the total compensation of the manager by adding their salary and bonus.
- 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.
- The calculate_total_compensation method is called on the manager object, which calculates the total compensation by adding the salary and bonus.
- The total compensation is then printed using the print statement.
- 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 Customer with attributes name and balance.
Create a Python class called VIPCustomer that inherits from the Customer class.
Create a Python class called Phone with attributes brand, model, and storage.
Create a Python class called Laptop with attributes brand, model, and storage.
Create a Python class called Book with attributes title, author, and pages.
Create a Python class called EBook that inherits from the Book class.