Python creating an Employee class with employee ID, name, salary attributes and implementing ID lookup
We will create a class named Employee class, which includes employee ID (id), name (name), and salary (salary) attributes. In addition, we will implement a method get_employee_by_id, used to look up employee information by employee ID.
Example
class
Employee:
def
init
(
self
,
id
,
name
,
salary
)
:
self
.
id
=
id
self
.
name
=
name
self
.
salary
=
salary
def
get_employee_by_id
(
self
,
id
)
:
if
self
.
id
==
id
:
return
self
else
:
return
None
Create several Employee objects
employee1
=
Employee
(
1
,
"Alice"
,
50000
)
employee2
=
Employee
(
2
,
"Bob"
,
60000
)
employee3
=
Employee
(
3
,
"Charlie"
,
70000
)
Query the employee with ID 2
result
=
employee1.
get_employee_by_id
(
2
)
if
result:
(
f
"Employee found: {result.name}, Salary: {result.salary}"
)
else
:
(
"Employee not found"
)
Code analysis:
EmployeeThe class's__init__method is used to initialize the object's attributes:id、nameandsalary。get_employee_by_idmethod is used to look up, based on the passed-in employee ID,idemployee information. If the current object'sidmatches the passed-inid, it returns the object; otherwise it returnsNone。- We created three
Employeeobject:employee1、employee2andemployee3。 - Use
employee1.get_employee_by_id(2)queried the employee information for ID 2 and printed the result.
Output result:
Employee found: Bob, Salary: 60000
Python3 Examples