Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python creating an Employee class with employee ID, name, salary attributes and implementing ID lookup

Python creating an Employee class with employee ID, name, salary attributes and implementing ID lookup

Document Object Reference Manual Python3 Examples

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:

   

print

(

f

"Employee found: {result.name}, Salary: {result.salary}"

)

else

:

   

print

(

"Employee not found"

)

Code analysis:

  1. Employee The class's __init__ method is used to initialize the object's attributes:id、name and salary。
  2. get_employee_by_id method is used to look up, based on the passed-in employee ID, id employee information. If the current object's id matches the passed-in id , it returns the object; otherwise it returns None。
  3. We created three Employee object:employee1、employee2 and employee3。
  4. 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

Document Object Reference Manual Python3 Examples