Python Create an Employee class, containing attributes such as employee ID, name, and salary, and implement employee ID lookup functionality
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")
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:
EmployeeThe class's__init__method is used to initialize the object's attributes:id、nameandsalary。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。- We created three
Employeeobjects:employee1、employee2andemployee3。 - Use
employee1.get_employee_by_id(2)to query the employee information with ID 2, and print the result.
Output result:
Employee found: Bob, Salary: 60000Other extensions
Python3 Examples