Employee Class using Instance & Class Variables

Challenge: Employee Class using Instance & Class Variables

Objective: Create an Employee class that uses both instance variables and a class variable.


1. Class Properties (Variables)

  • Instance Variables: (Unique to each employee object)
    • name
    • salary
    • designation
    • employee_id (Automatically assigned, not taken as a parameter)
  • Class Variable: (Shared across all employee objects)
    • employee_count
    • Initial Value: 101
    • Purpose: Used to automatically generate the next employee ID.

2. Employee ID Rules

  • The first employee ID should be E101.
  • The next should be E102, and so on.
  • The ID must be assigned automatically when a new employee object is created.
  • The employee_count class variable must be incremented after assigning an ID.

3. Class Methods (Functions)

  • __init__(self, name, salary, designation)
    • Takes namesalary, and designation as parameters.
    • Does NOT take employee_id as a parameter.
    • Inside this function:
      • Assigns an employee_id using the current employee_count (e.g., “E101”).
      • Increments the employee_count class variable for the next employee.
  • show_details(self)
    • Prints all the details of the employee: Name, Salary, Employee ID, and Designation.
  • total_employees(cls) (A Class Method)
    • Correction: This must be a class method, not a static method.
    • Purpose: Returns the total number of employees created.
    • Logic: Calculate total employees as employee_count - 101.

4. Key Summary

  • Use a class variable (employee_count) to auto-generate IDs.
  • Use instance variables to store individual employee details.
  • Implement three methods__init__show_details, and the class method total_employees.

class Employee:

    employee_count = 101

    def __init__(self, name, desig, sal):
        self.name = name
        self.designation = desig
        self.salary = sal
        self.eid = 'e' + str(Employee.employee_count)
        Employee.employee_count += 1

    def show_details(self):
        print('Name:',self.name)
        print('Eid:',self.eid)
        print('Designation:',self.designation)
        print('Salary:',self.salary)

    @classmethod
    def total_emp(cls):
        return cls.employee_count - 101


e1 = Employee('John', 'Manager', 10000)
e2 = Employee('Mark', 'Team Leader', 8000)

e1.show_details()
print('')
e2.show_details()
print('Total Employees:', e1.total_emp())

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *