Python员工信息管理系统代码
时间: 2024-06-17 08:01:47 浏览: 292
创建一个简单的Python员工信息管理系统代码示例可能包括以下几个步骤和组成部分:
1. **类定义**:
- 定义一个Employee类,包含属性如name, id, department等以及方法如`__init__`, `get_info`, `update_info`等。
```python
class Employee:
def __init__(self, id, name, department):
self.id = id
self.name = name
self.department = department
def get_info(self):
return f"ID: {self.id}, Name: {self.name}, Department: {self.department}"
def update_info(self, new_name=None, new_department=None):
if new_name:
self.name = new_name
if new_department:
self.department = new_department
```
2. **数据存储**:
- 可能会用到字典或列表来模拟数据库,员工信息以键值对的形式存储。
```python
employees = {} # 使用字典,键为id,值为Employee对象
```
3. **添加、查询和更新员工**:
- 提供方法来添加新员工,查询特定员工的信息,以及更新员工信息。
```python
def add_employee(employee):
employees[employee.id] = employee
def get_employee_info(employee_id):
if employee_id in employees:
return employees[employee_id].get_info()
else:
return "Employee not found."
def update_employee(employee_id, new_info):
if employee_id in employees:
for key, value in new_info.items():
if hasattr(employees[employee_id], key):
setattr(employees[employee_id], key, value)
else:
print("Employee not found.")
```
4. **主函数和用户界面**:
- 创建一个简单的命令行界面让用户交互。
```python
def main():
while True:
print("\n1. Add employee")
print("2. View employee info")
print("3. Update employee info")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
id = int(input("Enter employee ID: "))
name = input("Enter employee name: ")
department = input("Enter department: ")
new_employee = Employee(id, name, department)
add_employee(new_employee)
elif choice == "2":
id = int(input("Enter employee ID to view: "))
print(get_employee_info(id))
elif choice == "3":
id = int(input("Enter employee ID to update: "))
new_info = {}
if input("Update name? (y/n): ").lower() == "y":
new_info["name"] = input("New name: ")
if input("Update department? (y/n): ").lower() == "y":
new_info["department"] = input("New department: ")
update_employee(id, new_info)
elif choice == "4":
break
else:
print("Invalid choice.")
if __name__ == "__main__":
main()
```
阅读全文