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)
namesalarydesignationemployee_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ย
name,ยsalary, 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.
- Assigns anย
- Takesย
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())