Python Program to Manage Employees Using a Class
Intermediate · Classes and objects
This program manages a small team with an Employee class. Each employee gets an ID automatically, stores a name, a role and a monthly salary, and can be given a raise. The program then prints the team as a table with the total and average salary.
Program
ID Name Role Salary 101 Anita Manager Rs. 85000 102 Rahul Developer Rs. 66000 103 Sneha Designer Rs. 52000 Total monthly salaries: Rs. 203000 Average salary: Rs. 67666
How it works
next_idis a class attribute, shared by every employee, so each new object takes the next number as itsemp_idand then moves the counter on.__init__stores the name, role and salary in each object, alongside its ID.give_raise(10)raises one employee's salary by 10%, from Rs. 60000 to Rs. 66000, and the other objects are not affected.show()prints one row of the table, and padding such as:<7in the f-string keeps the columns lined up.- The total and the average are worked out from the list of objects, and
//gives the average in whole rupees.
Other ways to write it
A Manager class that inherits from Employee
Rahul: Rs. 720000 a year Anita: Rs. 1120000 a year
A manager is an employee with a bonus, so Manager inherits everything from Employee and only changes how the yearly pay is worked out.
Sorting and filtering employees
Highest paid first: Anita 85000 Sneha 72000 Rahul 60000 Vikram 48000 IT department: ['Rahul', 'Sneha']
sorted() with key=lambda e: e.salary orders the objects by salary, and a list comprehension picks out the employees of one department.
Try it yourself
Add a method annual_salary() that returns 12 times the monthly salary, and print it for each employee.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises