编写一个包含定义、执行的代码块,实现以下功能:根据部门编号变量的值输出本部门所有员工的平均工资。
时间: 2025-01-04 20:38:40 浏览: 5
假设我们有一个简单的员工类(Employee)和一个部门类(Department),每个部门都有一个员工列表(employees)以及一个计算平均工资的方法。以下是Python代码实现:
```python
class Employee:
def __init__(self, id, name, salary):
self.id = id
self.name = name
self.salary = salary
class Department:
def __init__(self, department_id):
self.department_id = department_id
self.employees = []
def add_employee(self, employee):
self.employees.append(employee)
def average_salary(self):
if not self.employees:
return "No employees in this department."
else:
total_salary = sum(employee.salary for employee in self.employees)
return total_salary / len(self.employees)
# 创建示例数据
dept1 = Department(1)
dept1.add_employee(Employee(101, 'Alice', 5000))
dept1.add_employee(Employee(102, 'Bob', 6000))
dept2 = Department(2)
dept2.add_employee(Employee(201, 'Charlie', 7000))
dept2.add_employee(Employee(202, 'Dave', 8000))
# 根据部门编号获取并计算平均工资
def get_department_average_salary(department_id):
try:
target_dept = [dept for dept in departments if dept.department_id == department_id][0]
return target_dept.average_salary()
except IndexError:
return "Department with the specified ID does not exist."
departments = [dept1, dept2] # 部门集合
department_number = 1 # 示例部门编号
average_salary = get_department_average_salary(department_number)
print(f"The average salary in Department {department_number} is: {average_salary}")
阅读全文