While working on Unit 10, Lesson 1, Exercise 14 - Review, I wrote a method for my student class that takes the average of the list of Grades it contains, with Grade being a class I wrote that contains a score. I solved the exercise successfully with an accumulating loop like so:
def get_average(self): grade_sum = 0 for grade in self.grades: grade_sum += grade.score return grade_sum / len(self.grades)
What I’m wondering, however, is if I can represent my grade class in such a way that I could instead write that method as:
def get_average(self): return sum(self.grades) / len(self.grades)
Python’s sum() won’t work on my Grade type, throwing a TypeError (and understandably so). I know that the repr dunder method can be used to return a string representation of a class, but I want to find a way to allow my Grade class to be interpreted as the integer value in my_grade.score for simplified use inside other functions. I’ve tried a variety of
ugly hacks potential solutions, but nothing has worked so far. The most promising route seems to be the dunder methods __add__ and __radd__, but neither the explanations I found nor the python documentation make it clear to me how these methods are used.
Here’s the complete code for context:
class Student: def __init__(self, name, year): self.name = name self.year = year self.grades =  def add_grade(self, grade): if type(grade) == Grade: self.grades.append(grade) def get_average(self): grade_sum = 0 for grade in self.grades: grade_sum += grade.score return grade_sum / len(self.grades) # return sum(self.grades) / len(self.grades) <- This is what I want to implement class Grade: minimum_passing = 65 def __init__(self, score): self.score = score def is_passing(self): return self.score >= self.minimum_passing pieter = Student('Pieter Bruegel the Elder', 'year 8') grade_1 = Grade(100) grade_2 = Grade(44) grade_3 = Grade(70) pieter.add_grade(grade_1) pieter.add_grade(grade_2) pieter.add_grade(grade_3) print(pieter.get_average())