Python 创建一个 Employee 类,包含工号、姓名、薪水等属性,并实现工号查询功能
我们将创建一个名为 Employee
的类,该类包含工号(id
)、姓名(name
)和薪水(salary
)三个属性。此外,我们还将实现一个方法 get_employee_by_id
,用于根据工号查询员工信息。
实例
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
# 创建几个 Employee 对象
employee1 = Employee(1, "Alice", 50000)
employee2 = Employee(2, "Bob", 60000)
employee3 = Employee(3, "Charlie", 70000)
# 查询工号为 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
# 创建几个 Employee 对象
employee1 = Employee(1, "Alice", 50000)
employee2 = Employee(2, "Bob", 60000)
employee3 = Employee(3, "Charlie", 70000)
# 查询工号为 2 的员工
result = employee1.get_employee_by_id(2)
if result:
print(f"Employee found: {result.name}, Salary: {result.salary}")
else:
print("Employee not found")
代码解析:
Employee
类的__init__
方法用于初始化对象的属性:id
、name
和salary
。get_employee_by_id
方法用于根据传入的工号id
来查询员工信息。如果当前对象的id
与传入的id
匹配,则返回该对象;否则返回None
。- 我们创建了三个
Employee
对象:employee1
、employee2
和employee3
。 - 使用
employee1.get_employee_by_id(2)
查询工号为 2 的员工信息,并打印结果。
输出结果:
Employee found: Bob, Salary: 60000
点我分享笔记