【问题标题】:How do I copy an employee information from one dictionary to another?如何将员工信息从一本字典复制到另一本字典?
【发布时间】:2021-03-15 02:15:32
【问题描述】:

我正在使用 Python 类 Employee 来复制员工管理系统中的 create employees 和 pickle 到一个文件。我让它工作正常,但我的导师希望能够搜索系统,即使是已删除的员工。我的问题是如何将对象从employeeDictionary 复制到deletedemployeeDictionary?我总是遇到错误。

这是我的员工类:

class Employee:
# Initialize Employee object
def __init__(self, name, ID, department, job):
    self.__ID = ID
    self.__name = name
    self.__department = department
    self.__job = job

# Set each object
def set_name(self, name):
    self.__name = name

def set_ID(self, ID):
    self.__ID = ID

def set_dept(self, department):
    self.__department = department

def set_job(self, job):
    self.__job = job

# Get each object
def get_name(self):
    return self.name

def get_ID(self):
    return self.__ID

def get_department(self):
    return self.__department

def get_job(self):
    return self.__job

def __str__(self):
    return (f"ID Number: {self.__ID}\nName: {self.__name}\n"
            f"Department: {self.__department}\n Job Title: {self.__job}")

这是我的主要代码:

import pickle
import emp2

def main():
    # Try to open the existing dictionary file
    try:
        inputFile1 = open('employee.pickle', 'rb')
        employeeDictionary = pickle.load(inputFile1)
        inputFile1.close()
        inputFile2 = open('deletedEmployee.pickle', 'rb')
        deletedEmployeeDictionary = pickle.load(inputFile2)
        inputFile2.close()

    except:
        employeeDictionary = {}
        deletedEmployeeDictionary = {}

   # While loop to continue until user chooses to quit
    proceed = True
    while proceed:

        # Display user's option menu and ask for a choice
        print('\n Employee Management System\n')
        print('\t1. Lookup an employee')
        print('\t2. Add a new employee')
        print('\t3. Change an existing employee')
        print('\t4. Delete an existing employee')
        print('\t5. Save and Quit\n')
        
        choice = int(input('Enter an option to continue: '))
        
        if choice == 1:
            lookup (employeeDictionary, deletedEmployeeDictionary)
        elif choice ==2:
            add(employeeDictionary)
        elif choice == 3:
            change (employeeDictionary)
        elif choice == 4:
            delete (employeeDictionary, deletedEmployeeDictionary)
        elif choice == 5:
            save_quit(employeeDictionary, deletedEmployeeDictionary)
            proceed = False
        else:
            print ('Invalid input!')
            choice = int(input('Enter an option to continue: '))

# Lookup an employee
def lookup(dictionary, dictionary2):
    # Look up the ID number if it is in the dictionary
    employee_id = int(input('Enter the employee ID number: '))
    if employee_id in dictionary:
        # print('employee_id', ': ', dictionary[employee_id])
        print(dictionary.get(employee_id))
    elif employee_id in dictionary2:
        # print('employee_id', ': ', dictionary2[employee_id])
        print(dictionary2.get(employee_id))
    else:
        print("That ID number was not found.")


# Add an employee
def add(dictionary):
    # Add a new employee
    empyloyee_id = int(input('Enter the employee ID number: '))
    if empyloyee_id not in dictionary.keys():
        name = input('Enter the name of the employee: ')
        dept = input('Enter the employee department: ')
        job = input('Enter the employee job title: ')
        entry = emp2.Employee(name, empyloyee_id, dept, job)
        dictionary[empyloyee_id] = entry
        print('Employee added succesfully')
    else:
        print('Employee already exists!')

# Change an employee
def change(dictionary):
    # If user-entered ID is in dictionary, allow them to change the info
    employee_id = int(input(
        'Enter the employee ID you would like to change: '))
    if employee_id in dictionary.keys():
        name = input('Enter new employee name: ')
        dept = input('Enter new employee department: ')
        job = input('Enter new employee job title: ')
        entry = emp2.Employee(name, employee_id, dept, job)
        dictionary[employee_id] = entry
        print('Employee changed successfully.')
    else:
        print('That employee ID was not found.')

# Delete an employee
def delete(dictionary, dictionary2):
    # If user-entered ID is in dictionary, delete the entry
    employee_id = int(input(
        'Enter the employee ID you would like to remove: '))
    if employee_id in dictionary.keys():
        entry = emp2.Employee(dictionary[employee_id])
        dictionary2[empyloyee_id] = entry
        del dictionary[employee_id]
        print('Employee successfully moved to deleted directory!')
    else:
        print('That employee ID was not found.')



# Save the dictionary and quit the program
def save_quit(dictionary, dictionary2):
    # Pickle the dictionary and save to a file
    outputFile1 = open('employee.pickle', 'wb')
    pickle.dump(dictionary, outputFile1)
    outputFile1.close
    # Pickle the dictionary and save to a file
    outputFile2 = open('deletedEmployee.pickle', 'wb')
    pickle.dump(dictionary2, outputFile2)
    outputFile2.close

def move(dictionary, dictionary2, employee_id):
    empyloyee_id = dictionary.get(employee_id)
    name = dictionary.get(name)
    dept = dictionary.get(department)
    job = dictionary.get(job)
    
    entry = emp2.Employee(name, empyloyee_id, dept, job)
    dictionary2[empyloyee_id] = entry
    
#Calls main function.   
if __name__== '__main__':
    main()

【问题讨论】:

  • 什么样的错误?更加详细一些。在您的帖子中包含错误的回溯。您是否希望人们通读您的整个代码并猜测错误可能来自哪里?

标签: python class dictionary object pickle


【解决方案1】:

您有几件需要更新。

  1. 在您的查找功能中,您不会通知用户该员工是否在活动列表或已删除列表中。您可能想让他们知道。

  2. 我将您的 MOVE 功能移至删除功能上方。由于您的 DELETE 函数需要移动调用,因此在 DELETE 之上设置 MOVE 可以处理该函数一次。

  3. 在您的 DELETE 中,我们更新了脚本以允许 MOVE 发生,然后我们可以使用 POP 功能从花名册中删除对象。

import pickle
import employee as emp2


def main():
    # Try to open the existing dictionary file
    try:
        inputFile1 = open('employee.pickle', 'rb')
        employeeDictionary = pickle.load(inputFile1)
        inputFile1.close()
        inputFile2 = open('deletedEmployee.pickle', 'rb')
        deletedEmployeeDictionary = pickle.load(inputFile2)
        inputFile2.close()

    except:
        employeeDictionary = {}
        deletedEmployeeDictionary = {}

    # While loop to continue until user chooses to quit
    proceed = True
    while proceed:

        # Display user's option menu and ask for a choice
        print('\n Employee Management System\n')
        print('\t1. Lookup an employee')
        print('\t2. Add a new employee')
        print('\t3. Change an existing employee')
        print('\t4. Delete an existing employee')
        print('\t5. Save and Quit\n')

        choice = int(input('Enter an option to continue: '))

        if choice == 1:
            lookup(employeeDictionary, deletedEmployeeDictionary)
        elif choice == 2:
            add(employeeDictionary)
        elif choice == 3:
            change(employeeDictionary)
        elif choice == 4:
            delete(employeeDictionary, deletedEmployeeDictionary)
        elif choice == 5:
            save_quit(employeeDictionary, deletedEmployeeDictionary)
            proceed = False
        else:
            print('Invalid input!')
            choice = int(input('Enter an option to continue: '))


# Lookup an employee
def lookup(dictionary, dictionary2):
    # Look up the ID number if it is in the dictionary
    employee_id = int(input('Enter the employee ID number: '))
    if employee_id in dictionary:
        # print('employee_id', ': ', dictionary[employee_id])
        print('Active Record...')
        print(dictionary.get(employee_id))
    elif employee_id in dictionary2:
        # print('employee_id', ': ', dictionary2[employee_id])
        print("Deleted Record...")
        print(dictionary2.get(employee_id))
    else:
        print("That ID number was not found.")


# Add an employee
def add(dictionary):
    # Add a new employee
    empyloyee_id = int(input('Enter the employee ID number: '))
    if empyloyee_id not in dictionary.keys():
        name = input('Enter the name of the employee: ')
        dept = input('Enter the employee department: ')
        job = input('Enter the employee job title: ')
        entry = emp2.Employee(name, empyloyee_id, dept, job)
        dictionary[empyloyee_id] = entry
        print('Employee added succesfully')
    else:
        print('Employee already exists!')


# Change an employee
def change(dictionary):
    # If user-entered ID is in dictionary, allow them to change the info
    employee_id = int(input(
        'Enter the employee ID you would like to change: '))
    if employee_id in dictionary.keys():
        name = input('Enter new employee name: ')
        dept = input('Enter new employee department: ')
        job = input('Enter new employee job title: ')
        entry = emp2.Employee(name, employee_id, dept, job)
        dictionary[employee_id] = entry
        print('Employee changed successfully.')
    else:
        print('That employee ID was not found.')

def move(dictionary, dictionary2, employee_id):
    dictionary2[employee_id] = dictionary.get(employee_id)

# Delete an employee
def delete(dictionary, dictionary2):
    # If user-entered ID is in dictionary, delete the entry
    employee_id = int(input(
        'Enter the employee ID you would like to remove: '))
    if employee_Id in dictionary:
         move(dictionary, dictionary2, employee_id)
         dictionary.pop(employee_id)
         print('Employee successfully moved to deleted directory!')
    else:
         print('Employee not in directory!')

# Save the dictionary and quit the program
def save_quit(dictionary, dictionary2):
    # Pickle the dictionary and save to a file
    outputFile1 = open('employee.pickle', 'wb')
    pickle.dump(dictionary, outputFile1)
    outputFile1.close
    # Pickle the dictionary and save to a file
    outputFile2 = open('deletedEmployee.pickle', 'wb')
    pickle.dump(dictionary2, outputFile2)
    outputFile2.close





# Calls main function.
if __name__ == '__main__':
    main()

【讨论】:

  • 谢谢,它成功了。我会听取您的建议通知用户。我从来没有真正考虑过放入函数的顺序,但是谢谢我会记住的。再次感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多