What’s going wrong despite using “grade.score” to append “self.grades”

Can anyone help me out with my code below, I don’t get what’s going wrong despite using “grade.score” to append “self.grades”:

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.score)

  def get_average(self):
    return sum(self.grades) / len(self.grades)      

class Grade:

  def __init__(self, score):
    self.score = score
    
pieter = Student("Pieter Bruegel the Elder", 8)

pieter.add_grade(Grade(100))
pieter.add_grade(Grade(70))

print(pieter.get_average)
print(pieter.grades)
print(sum(pieter.grades) / len(pieter.grades))

For some reason the following is printed for my first print command:
“<bound method Student.get_average of <main.Student object at 0x7fbc60427828>>”

Whereas for the following two print commands I do print a list of int and get a proper average:
[100, 70]
85.0

This is what I expect. Please help!!

That is a method call so should have () to invoke it.

1 Like

of course! ■■■■, thanks a lot, especially for the prompt reply.

Much appreciated!!

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_score = [element.score for element in self.grades]
    return sum(grade_score)/len(grade_score)

class Grade:

  def __init__(self, score):
    self.score = score
    
pieter = Student("Pieter Bruegel the Elder", 8)

pieter.add_grade(Grade(100))
pieter.add_grade(Grade(70))

print(pieter.grades[0].score)
print(pieter.get_average())

So I think I figured out how to calculate the average score while using objects of the class Grade to append “self.grades”, see code above.

Just for my deeper understanding; what is the point of creating a custom class for Grade if in the end we convert back to integer datatype for the calculations anyway?

It permits us to give Grade object special methods of their own, such as is_passing() which should come up in the exercise.

1 Like