打印和更改特定数据

时间:2018-05-06 00:36:33

标签: class object instances

我正在处理python的一项任务,这给我带来了一些麻烦。 我创建了一个为课堂上的学生提供数据的课程。

我需要做以下事情:

  1. 查找并仅显示特定学生的gpa。
  2. 在课堂上添加新学生。
  3. 更改学生的GPA。
  4. 更改学生的预期成绩。
  5. 以表格格式打印所有学生的数据。
  6. 退出程序,并保存您创建的所有文件。
  7. 到目前为止,我已设法锁定打印数据。保存和退出按预期工作。

    我在菜单选项1 - 4上遇到错误,错误各不相同。这是我第一次真正被难倒,需要得到一些专家的帮助。这本书不太好。

    例如,函数add_student返回了两个单独的错误:

    设置entry = student.Student(name, studentid, gpa, expgrade, status)

      我收到错误NameError: name student is not defined

    如果我尝试Student(name, studentid, gpa, expgrade, status)   我收到错误TypeError: argument of type 'Student' is not iterable.

    class Student:
        def __init__(self, name, studentid, gpa, expgrade, status):
    
            self.__name = name
            self.__studentid = studentid
            self.__gpa = gpa
            self.__expgrade = expgrade
            self.__status = status
    
        def set_name(self, name):
            self.__name = name
    
        def set_studentid(self, studentid):
            self.__studentid = studentid
    
        def set_gpa(self, gpa):
            self.__gpa = gpa
    
        def set_expgrade(self, expgrade):
            self.__expgrade = expgrade
    
        def set_status(self, status):
            self.__status
    
        def get_name(self):
            return self.__name
    
        def get_studentid(self):
            return self.__studentid
    
        def get_gpa(self):
            return self.__gpa
    
        def get_expgrade(self):
            return self.__expgrade
    
        def get_status(self):
            return self.__status
    
        def __str__(self):
            return 'Name:' + self.__name + \
                   '\nId Number:' + self.__studentid + \
                   '\nGPA: ' + self.__gpa + \
                   '\nExpected Grade: ' + self.__expgrade + \
                   '\nEnrollment Status: ' + self.__status
    
    
    
    
    
    
    
    
    
    import pickle
    LOOK_UP = 1
    ADD_STUDENT = 2
    CHANGE_GPA = 3
    CHANGE_EXPGRADE = 4
    PRINT_DATA = 5
    QUIT = 6
    
    FILENAME = 'students.dat'
    
    
    def main():
        st_1 = Student('Ryan Galloway', '2223344', '3.9', 'A', 'FT')
        st_2 = Student('Renee Polanco', '2345432', '4.0', 'A', 'PT')
        st_3 = Student('Jane Doe', '3245655', '2.2', 'C', 'PT')
        st_4 = Student('John Doe', '1234567', '3.0', 'B', 'FT')
        st_5 = Student('Marvin Martian', '0987568', '1.8', 'F', 'PT')
        output_file = open(FILENAME, 'wb')
        pickle.dump(st_1, output_file)
        pickle.dump(st_2, output_file)
        pickle.dump(st_3, output_file)
        pickle.dump(st_4, output_file)
        pickle.dump(st_5, output_file)
        output_file.close()
    
        students = load_students()
    
        choice = 0
    
        while choice != QUIT:
            choice = get_menu_choice()
    
            if choice == LOOK_UP:
                look_up(students)
            elif choice == ADD_STUDENT:
                add_student(students)
            elif choice == CHANGE_GPA:
                change_gpa(students)
            elif choice == CHANGE_EXPGRADE:
                change_expgrade(students)
            elif choice == PRINT_DATA:
                print_data(students)
            elif choice == QUIT:
                save(students)
    
    def load_students():
        try:
            input_file = open(FILENAME, 'rb')
    
            student_dct = pickle.load(input_file)
    
            input_file.close
    
        except IOError:
            student_dct = {}
    
        return student_dct
    
    def get_menu_choice():
        print()
        print('Menu')
        print('--------------------------')
        print("1. Look up and display a student's GPA")
        print("2. Add a new student")
        print("3. Change the GPA of a student")
        print("4. Change the expected grade of a student")
        print("5. Print all student data")
        print("6. Quit the program and save information")
        print()
    
        try:
            choice = int(input('Enter your choice: '))
    
            while choice < LOOK_UP or choice > QUIT:
                choice = int(input('Enter a valid choice: '))
            return choice
        except ValueError:
            print('That is not a valid input. Please restart the program.')
    
    def look_up(students):
        name = input('Enter the student name: ')
        if name in students:
            print(students.gpa)
        else:
            print('That name does not exist.')
    
    
    def add_student(students):
        name = input('Name: ')
        studentid = input('Student ID number: ')
        gpa = input('GPA: ')
        expgrade = input('Expected Grade: ')
        status = input('Full Time (FT) or Part Time(PT): ')
    
        entry = student.Student(name, studentid, gpa, expgrade, status)
    
        if name not in students:
            student[name] = entry
        else:
            print('That student is already logged.')
    
    def change_gpa(students):
    
        name = input('Enter a student name: ')
    
        if name in students:
            gpa = input('Enter the new GPA: ')
    
            entry = Student(name, studentid, gpa, expgrade, status)
    
            students[name] = entry
            print('Information updated.')
        else:
            print('That name is not found.')
    
    def change_expgrade(students):
        name = input('Enter a name: ')
    
        if name in students:
            expgrade = input('Enter the new expected grade for the student: ')
            entry = Student(name, studentid, gpa, expgrade, status)
            students[name] = entry
        else:
            print('That name was not found.')
    
    def print_data(students):
        end_of_file = False
    
        input_file = open(FILENAME, 'rb')
        try:
            while not end_of_file:
                student_data = pickle.load(input_file)
                display_data(student_data)
        except EOFError:
            end_of_file = True
        input_file.close()
    
    
    
    def save(students):
        output_file = open(FILENAME, 'wb')
    
        pickle.dump(students, output_file)
    
        output_file.close()
    
    def display_data(student_data):
        print('Name: ', student_data.get_name())
        print('Student ID: ' , student_data.get_studentid())
        print('GPA: ', student_data.get_gpa())
        print('Expected Grade: ', student_data.get_expgrade())
        print('Enrollment Status: ', student_data.get_status())
        print()
    
    
    main()
    

2 个答案:

答案 0 :(得分:0)

查看代码后,我发现了一些事情:

  1. 你真的不需要Student上的所有那些getter和setter - 只需使用属性本身(没有下划线)。那里的数据并非真正私密,只是以不同的名义公开。 (这应该有助于你更好地理解课程。)
  2. change_foo方法中,您在改变什么? (我会给你一个提示:你不能通过创造它们来改变它们。; - ))
  3. look_up方法中,students(注意名称)是否有GPA?或者更重要的是,它甚至是学生吗?
  4. 您忘记了实际关闭文件。您应该能够找出我所指的地方,但为了将来参考,在Python中,最好这样做:with open(some_file, 'r') as file: make_spam()(这是一个缩进的块语句,如iftry以及as whatever是可选的。)
  5. 这可能不一定能解决所有你的错误,但它绝对应该让你有一个良好的开端和一些关于如何克服其余错误的想法。

答案 1 :(得分:0)

将此问题发布给遇到此任务且遇到问题的其他任何人。

这是我使用getter和setter修正的代码,并创建一个包含要写入.dat文件的对象的列表。问题是它试图迭代类,而不是我之前写过的方式。

还使用for循环迭代对象,效果很好。

class StudentClass:
 def __init__(self, name, studentid, gpa, expgrade, status):

    self.__name = name
    self.__studentid = studentid
    self.__gpa = gpa
    self.__expgrade = expgrade
    self.__status = status

 def set_name(self, name):
    self.__name = name

 def set_studentid(self, studentid):
    self.__studentid = studentid

 def set_gpa(self, gpa):
    self.__gpa = gpa

 def set_expgrade(self, expgrade):
    self.__expgrade = expgrade

 def set_status(self, status):
    self.__status

 def get_name(self):
    return self.__name

 def get_studentid(self):
    return self.__studentid

 def get_gpa(self):
    return self.__gpa

 def get_expgrade(self):
    return self.__expgrade

 def get_status(self):
    return self.__status

 def __str__(self):
    return 'Name: ' + self.__name + \
           '\nId Number: ' + self.__studentid + \
           '\nGPA: ' + self.__gpa + \
           '\nExpected Grade: ' + self.__expgrade + \
           '\nEnrollment Status: ' + self.__status



import pickle

LOOK_UP = 1
ADD_STUDENT = 2
CHANGE_GPA = 3
CHANGE_EXPGRADE = 4
PRINT_DATA = 5
QUIT = 6

FILENAME = 'students.dat'


def main():
    st_1 = StudentClass('Ryan Galloway', '2223344', '3.9', 'A', 'FT')
    st_2 = StudentClass('Renee Polanco', '2345432', '4.0', 'A', 'PT')
    st_3 = StudentClass('Jane Doe', '3245655', '2.2', 'C', 'PT')
    st_4 = StudentClass('John Doe', '1234567', '3.0', 'B', 'FT')
    st_5 = StudentClass('Marvin Martian', '0987568', '1.8', 'F', 'PT')
    student_objects = [st_1, st_2, st_3, st_4, st_5]
    output_file = open(FILENAME, 'wb')
    pickle.dump(student_objects, output_file)
    output_file.close()


students = load_students()

choice = 0

while choice != QUIT:
    choice = get_menu_choice()

    if choice == LOOK_UP:
        look_up(students)
    elif choice == ADD_STUDENT:
        add_student(students)
    elif choice == CHANGE_GPA:
        change_gpa(students)
    elif choice == CHANGE_EXPGRADE:
        change_expgrade(students)
    elif choice == PRINT_DATA:
        print_data(students)
    elif choice == QUIT:
        save(students)




def get_menu_choice():
    print()
    print('Menu')
    print('--------------------------')
    print("1. Look up and display a student's GPA")
    print("2. Add a new student")
    print("3. Change the GPA of a student")
    print("4. Change the expected grade of a student")
    print("5. Print all student data")
    print("6. Quit the program and save information")
    print()

    try:
        choice = int(input('Enter your choice: '))

        while choice < LOOK_UP or choice > QUIT:
            choice = int(input('Enter a valid choice: '))
        return choice
    except ValueError:
        print('That is not a valid input. Please restart the program.')

def load_students():
    try:
        input_file = open(FILENAME, 'rb')

        student_dct = pickle.load(input_file)

        input_file.close()

    except IOError:
        student_dct = {}

    return student_dct



def look_up(students):
    found = False
    name = input('Enter the student name: ')
    for student in students:
        if name.lower() == student.get_name().lower():
            print('GPA: ', student.get_gpa())
            found = True
    if not found:
        print(name, 'was not found.')


def add_student(students):
    name = input('Name: ')
    studentid = input('Student ID number: ')
    gpa = input('GPA: ')
    expgrade = input('Expected Grade: ')
    status = input('Full Time (FT) or Part Time(PT): ')

    entry = StudentClass(name, studentid, gpa, expgrade, status)

    found = False
    for student in students:
        if name.lower() == student.get_name().lower():
            found = True


    if not found:
        students.append(entry)

def change_gpa(students):

    name = input('Enter a student name: ')
    found = False
    for student in students:
        if name.lower() == student.get_name().lower():
            gpa = input('Enter the new GPA: ')
            found = True
            student.set_gpa(gpa)
            print('GPA has been updated.')

    if not found:
        print(name, 'was not found.')
def change_expgrade(students):
    name = input('Enter a name: ')
    found = True
    for student in students:
        if name.lower() == student.get_name().lower():
            found = True
            expgrade = input('Enter the new expected grade: ')
            student.set_expgrade = expgrade
            print('Expected grade updated.')
    if not found:
        print(name, 'was not found.')


def print_data(students):
    end_of_file = False

    input_file = open(FILENAME, 'rb')

    try:
        while not end_of_file:
            student_data = pickle.load(input_file)
            display_data(student_data)

    except EOFError:
        end_of_file = True
    input_file.close()



def save(students):
    output_file = open(FILENAME, 'wb')

    pickle.dump(students, output_file)

    output_file.close()

def display_data(student_data):
    print('Name: ', student_data.get_name())
    print('Student ID: ' , student_data.get_studentid())
    print('GPA: ', student_data.get_gpa())
    print('Expected Grade: ', student_data.get_expgrade())
    print('Enrollment Status: ', student_data.get_status())
    print()


main()