Python implementing an employee management system class
We will create a simple employee management system class that will allow us to add employees, delete employees, update employee information, and list all employee information. Each employee will have a unique ID, name, and position.
Example
class
EmployeeManagementSystem:
def
init
(
self
)
:
self
.
employees
=
{
}
def
add_employee
(
self
,
id
,
name
,
position
)
:
if
id
in
self
.
employees
:
return
"Employee ID already exists."
self
.
employees
[
id
]
=
{
'name'
: name
,
'position'
: position
}
return
"Employee added successfully."
def
remove_employee
(
self
,
id
)
:
if
id
not
in
self
.
employees
:
return
"Employee ID does not exist."
del
self
.
employees
[
id
]
return
"Employee removed successfully."
def
update_employee
(
self
,
id
,
name
=
None
,
position
=
None
)
:
if
id
not
in
self
.
employees
:
return
"Employee ID does not exist."
if
name:
self
.
employees
[
id
]
[
'name'
]
=
name
if
position:
self
.
employees
[
id
]
[
'position'
]
=
position
return
"Employee updated successfully."
def
list_employees
(
self
)
:
if
not
self
.
employees
:
return
"No employees found."
for
id
,
info
in
self
.
employees
.
items
(
)
:
(
f
"ID: {id}, Name: {info['name']}, Position: {info['position']}"
)
Example usage
ems
=
EmployeeManagementSystem
(
)
ems.
add_employee
(
1
,
'John Doe'
,
'Developer'
)
ems.
add_employee
(
2
,
'Jane Smith'
,
'Manager'
)
ems.
list_employees
(
)
ems.
update_employee
(
1
,
name
=
'Johnathan Doe'
)
ems.
list_employees
(
)
ems.
remove_employee
(
2
)
ems.
list_employees
(
)
Code analysis:
__init__method initializes an empty dictionaryemployeesto store employee information.add_employeemethod is used to add a new employee; if the employee ID already exists, it returns an error message.remove_employeemethod is used to delete an employee; if the employee ID does not exist, it returns an error message.update_employeemethod is used to update employee information; it can update the name or position, or both.list_employeesmethod is used to list all employee information; if there are no employees, it returns corresponding information.
Output result:
ID: 1, Name: John Doe, Position: Developer
ID: 2, Name: Jane Smith, Position: Manager
ID: 1, Name: Johnathan Doe, Position: Developer
ID: 2, Name: Jane Smith, Position: Manager
ID: 1, Name: Johnathan Doe, Position: Developer
Python3 Examples