【问题标题】:Python: How to add information to a dictionary using a class, then print key and values of added dictionary entryPython:如何使用类向字典添加信息,然后打印添加的字典条目的键和值
【发布时间】:2020-11-18 09:10:31
【问题描述】:

我正在处理以下任务,并且不熟悉使用类来创建/存储对象:

员工管理系统:本练习假设您已经为编程练习 4 创建了 Employee 类。创建一个将 Employee 对象存储在字典中的程序。使用员工 ID 号作为密钥。程序应该提供一个菜单,让用户执行以下操作:在字典中查找员工,向字典中添加新员工,更改字典中现有员工的姓名、部门和职位,删除员工字典,退出程序。 当程序结束时,它应该腌制字典并将其保存到文件中。每次 程序启动时,它应该尝试从文件中加载腌制字典。如果文件不存在, 程序应该以一个空字典开始。

一切都很顺利,直到我运行程序并且在使用员工查找功能时无法正确打印信息。运行代码时:

if ID in dictionary.keys():
    print(ID, ': ', dictionary[ID])

输出是:

1 :  <Employee.Employee object at 0x03520340>

我附上了一张我添加员工时正在运行的程序的图像,然后尝试查找它。我认为我最初在 add 函数中保存数据的方式可能存在问题,或者在查找函数中访问数据时存在问题。 是否有其他方法可以打印指定 ID 的字典内容?我是否一开始就错误地存储了对象属性?


作为参考,这是我的其余代码:

Employee.py(雇员类在它自己的文件中):

class Employee:
    # Initialize Employee object
    def __init__(self, ID, name, department, job):
        self.__name = name
        self.__ID = ID
        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 print(self):
        print("Name: " + self.__name + \
               ", ID Number: " + self.__ID + \
               ", Department: " + self.__department + \
               ", Job Title: " + self.__job)

EmployeeManagementSystem.py:

# Import necessary libraries
import pickle
import Employee
    
    
# STEP 1 = DEFINE FUNCTIONS FOR EACH CHOICE

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

    # Offer the user the menu of choices again from main()
    proceed = True
    return proceed


# Add an employee
def add(dictionary):
    # Add a new employee
    ID = int(input('Enter the employee ID number: '))
    name = input('Enter the name of the employee: ')
    dept = input('Enter the employee department: ')
    job = input('Enter the employee job title: ')
  
    entry = Employee.Employee(ID, name, dept, job)
    dictionary[ID] = entry
    print('Employee added succesfully')
   
    # Offer the user the menu of choices again from main()
    proceed = True
    return proceed
    
    
# Change an employee    
def change(dictionary):
    # If user-entered ID is in dictionary, allow them to change the info
    ID = input('Enter the employee ID you would like to change: ')
    if ID in dictionary.keys():
        name = input('Enter new employee name: ')
        newId = input('Enter new employee ID: ')
        dept = input('Enter new employee department: ')
        job = input('Enter new employee job title: ')
        entry = Employee.Employee(newID, name, dept, job)
        dictionary[ID] = entry
        print('Employee changed successfully.')
    else:
        print('That employee ID was not found.')
    
    # Offer the user the menu of choices again from main()
    proceed = True
    return proceed
    
    
# Delete an employee
def delete(dictionary):
    # If user-entered ID is in dictionary, delete the entry
    ID = input('Enter the employee ID you would like to remove: ')
    if ID in dictionary.keys():
        del dictionary[ID]
        print('Employee removed successfully')
    else:
        print('That employe ID was not found.')
 
    # Offer the user the menu of choices again from main()
    proceed = True
    return proceed
    
    
# Save the dictionary and quit the program
def save_quit(dictionary):
    # Pickle the dictionary and save to a file
    output_file = open('employee_data.dat','wb')
    pickle.dump(dictionary,output_file)
    output_file.close
    
        
    # End the while loop in main() so program quits
    proceed = False
    return proceed
# STEP 2 - Main Function
def main():

    # Try to open the existing dictionary file
    try:
        input_file = open('employee_data.dat','rb')
        employee_dictionary = pickle.load(input_file)
        input_file.close()

    # If no such file exists, create a new dictionary
    except:
        employee_dictionary = {}


    # 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')

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

        # Map each choice to the functions below using a dictionary
        options = {1:lookup, 2:add, 3:change, 4:delete, 5:save_quit,}
        proceed = options[option_choice](employee_dictionary)



# STEP 3 - CALL MAIN
# Call the main function
main()

【问题讨论】:

  • 你必须给员工添加一个__str__() 方法来告诉python如何打印它。 Python 不知道如何打印自定义类。
  • 我将之前的打印方法更改为带有 return 语句的 __str__(),但现在我得到一个“类型错误:只能将 str(而不是“int”)连接到 str'。我是否需要将员工 ID 转换为字符串才能打印?不知道如何在课堂上做到这一点。
  • 是的,您可以使用str(x) 将x 转为字符串。
  • 修复了 str 部分,但是当我从字典中打印任何内容时,它仍然显示 而不是信息

标签: python class dictionary object-oriented-database


【解决方案1】:
def lookup(dictionary):
    # Look up the ID number if it is in the dictionary
    ID = int(input('Enter the employee ID number: '))
    if ID in dictionary.keys():
        x=dictionary.get(ID)
        x.print()

    else:
        print("That ID number was not found.")

    # Offer the user the menu of choices again from main()
    proceed = True
    return proceed

因为你已经有了一个 print 调用函数 并且打印函数中存在错误,以修复将 'self.__id' 更改为 'str(self.__ID)'

    def print(self):
        print("Name: " + self.__name + \
               ", ID Number: " + str(self.__ID) + \
               ", Department: " + self.__department + \
               ", Job Title: " + self.__job)

【讨论】:

    【解决方案2】:

    您可以将Employee 类中的print 方法更改为__str__,如下所示:

    class Employee:
        # Initialize Employee object
        def __init__(self, ID, name, department, job):
            self.__name = name
            self.__ID = ID
            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"Name: {self.__name}, ID Number: {self.__ID}, "
                    f"Department: {self.__department}, Job Title: {self.__job}")
    

    还修正了EmployeeManagementSystem.py 文件中的一些小错误:

    # Import necessary libraries
    import pickle
    import Employee
    
    
    def get_int_input(prompt):
        num = -1
        while True:
            try:
                num = int(input(prompt))
                break
            except:
                print("Error: Enter an integer, try again...")
        return num
    
    
    # Lookup an employee
    def lookup(dictionary):
        # Look up the ID number if it is in the dictionary
        employee_id = get_int_input('Enter the employee ID number: ')
        if employee_id in dictionary:
            # print('employee_id', ': ', dictionary[employee_id])
            print(dictionary.get(employee_id))
        else:
            print("That ID number was not found.")
    
        # Offer the user the menu of choices again from main()
        proceed = True
        return proceed
    
    
    # Add an employee
    def add(dictionary):
        # Add a new employee
        empyloyee_id = get_int_input('Enter the employee ID number: ')
        name = input('Enter the name of the employee: ')
        dept = input('Enter the employee department: ')
        job = input('Enter the employee job title: ')
    
        entry = Employee.Employee(empyloyee_id, name, dept, job)
        dictionary[empyloyee_id] = entry
        print('Employee added succesfully')
    
        # Offer the user the menu of choices again from main()
        proceed = True
        return proceed
    
    
    # Change an employee
    def change(dictionary):
        # If user-entered ID is in dictionary, allow them to change the info
        employee_id = get_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 = Employee.Employee(employee_id, name, dept, job)
            dictionary[employee_id] = entry
            print('Employee changed successfully.')
        else:
            print('That employee ID was not found.')
    
        # Offer the user the menu of choices again from main()
        proceed = True
        return proceed
    
    
    # Delete an employee
    def delete(dictionary):
        # If user-entered ID is in dictionary, delete the entry
        employee_id = get_int_input(
            'Enter the employee ID you would like to remove: ')
        if employee_id in dictionary.keys():
            del dictionary[employee_id]
            print('Employee removed successfully')
        else:
            print('That employee ID was not found.')
    
        # Offer the user the menu of choices again from main()
        proceed = True
        return proceed
    
    
    # Save the dictionary and quit the program
    def save_quit(dictionary):
        # Pickle the dictionary and save to a file
        output_file = open('employee_data.dat', 'wb')
        pickle.dump(dictionary, output_file)
        output_file.close
    
        # End the while loop in main() so program quits
        proceed = False
        return proceed
    
    
    # STEP 2 - Main Function
    def main():
        # Try to open the existing dictionary file
        try:
            input_file = open('employee_data.dat', 'rb')
            employee_dictionary = pickle.load(input_file)
            input_file.close()
    
        # If no such file exists, create a new dictionary
        except:
            employee_dictionary = {}
    
        # 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')
    
            option_choice = get_int_input('Enter an option to continue: ')
    
            # Map each choice to the functions below using a dictionary
            options = {
                1: lookup,
                2: add,
                3: change,
                4: delete,
                5: save_quit,
            }
            proceed = options[option_choice](employee_dictionary)
    
    
    # STEP 3 - CALL MAIN
    # Call the main function
    main()
    

    示例用法:

     Employee Management System
    
        1. Lookup an employee
        2. Add a new employee
        3. Change an existing employee
        4. Delete an existing employee
        5. Save and Quit
    
    Enter an option to continue: 2
    Enter the employee ID number: 123
    Enter the name of the employee: asd
    Enter the employee department: asd
    Enter the employee job title: asd
    Employee added succesfully
    
     Employee Management System
    
        1. Lookup an employee
        2. Add a new employee
        3. Change an existing employee
        4. Delete an existing employee
        5. Save and Quit
    
    Enter an option to continue: 1
    Enter the employee ID number: 123
    Name: asd, ID Number: 123, Department: asd, Job Title: asd
    
     Employee Management System
    
        1. Lookup an employee
        2. Add a new employee
        3. Change an existing employee
        4. Delete an existing employee
        5. Save and Quit
    
    Enter an option to continue: 3
    Enter the employee ID you would like to change: asd
    Error: Enter an integer, try again...
    Enter the employee ID you would like to change: 123
    Enter new employee name: zxc
    Enter new employee department: zxc
    Enter new employee job title: zxc
    Employee changed successfully.
    
     Employee Management System
    
        1. Lookup an employee
        2. Add a new employee
        3. Change an existing employee
        4. Delete an existing employee
        5. Save and Quit
    
    Enter an option to continue: 1
    Enter the employee ID number: 123
    Name: zxc, ID Number: 123, Department: zxc, Job Title: zxc
    
     Employee Management System
    
        1. Lookup an employee
        2. Add a new employee
        3. Change an existing employee
        4. Delete an existing employee
        5. Save and Quit
    
    Enter an option to continue: 4
    Enter the employee ID you would like to remove: 123
    Employee removed successfully
    
     Employee Management System
    
        1. Lookup an employee
        2. Add a new employee
        3. Change an existing employee
        4. Delete an existing employee
        5. Save and Quit
    
    Enter an option to continue: 1
    Enter the employee ID number: 123
    That ID number was not found.
    
     Employee Management System
    
        1. Lookup an employee
        2. Add a new employee
        3. Change an existing employee
        4. Delete an existing employee
        5. Save and Quit
    
    Enter an option to continue: 5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-24
      • 2018-05-27
      • 1970-01-01
      • 2020-06-10
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多