Best place to add error handling for objects?

I have a class called "Student" that creates a basic student object complete with everything you need to release a GPA. I added two methods that relate to gradation and writing class, respectively, in order to then calculate the GPA. My question is what better method and placement would add error handling if they introduced a letter class that was unacceptable (i.e. G or X). Would I do this in the method itself or in the program, calling it more appropriate?

class Student:
    def __init__(self, name, hours, qpoints):
        self.name = name
        self.hours = float(hours)
        self.qpoints = float(qpoints)

    def get_name(self):
        return self.name

    def get_hours(self):
        return self.hours

    def get_qpoints(self):
        return self.qpoints

    def gpa(self):
        return self.qpoints / self.hours

    def add_grade(self, grade_point, credit_hours):
        self.qpoints += grade_point * credit_hours
        self.hours += credit_hours

    def add_letter_grade(self, grade_letter, credit_hours):
        letter_grades = {
            'A': 4.0,
            'B': 3.0,
            'C': 2.0,
            'D': 1.0,
            'F': 0.0
        }

        grade_point = letter_grades.get(grade_letter)
        self.qpoints += grade_point * credit_hours
        self.hours += credit_hours

def main():
    new_student = Student('Mike Smith', 0, 0)

while True:
    usr_input = input('Please enter the student course information'
                      ' (grade and credit hours) separated'
                      ' by a comma <q to quit>: ')
    if usr_input == 'q':
        break
    else:
        grade, hours = usr_input.split(',')
        if grade.isalpha():
            new_student.add_letter_grade(grade, float(hours))
        else:
            new_student.add_grade(float(grade), float(hours))

print('{0}\ final GPA was {1:.2f}'.format(new_student.get_name(), new_student.gpa()))


if __name__ == '__main__':
    main()
+4
source share
3 answers
grade_point = letter_grades.get(grade_letter)

Here you should run your error.

letter_grades.get(grade_letter) letter_grades[grade_letter]. KeyError .

,

try:
    new_student.add_letter_grade(grade, float(hours))
except KeyError:
    print("That looks like a letter grade, but we don't know what it means. Ignoring it.")

`` `

+3

. , , , , , .

Python raise . "" , , raise - . , , , .

- , .

+2

. ? ?

, . .

However, it is important to ensure that the check occurs at one or the other end. Both of them are very preferable for them.

Does it help at all?

+1
source

Source: https://habr.com/ru/post/1607513/


All Articles