Python Create an Employee class, containing attributes such as employee ID, name, and salary, and implement employee ID lookup functionality

Document 对象参考手册Python3 Examples

We will create a class namedEmployeethat contains the employee ID (id), name (name) and salary (salary) attributes. In addition, we will also implement a methodget_employee_by_id, which is used to query employee information by employee ID.

Examples

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. EmployeeThe class's__init__method is used to initialize the object's attributes:id、nameandsalary。
  2. get_employee_by_idThe method is used, based on the passed-in employee ID,idto query employee information. If the current object'sidand the passed-inidmatch, then return the object; otherwise returnNone。
  3. We created threeEmployeeobjects:employee1、employee2andemployee3。
  4. Useemployee1.get_employee_by_id(2)to query the employee information with ID 2, and print the result.

Output result:

Employee found: Bob, Salary: 60000

Document 对象参考手册Python3 Examples

Other extensions