Did anyone try the the bonus practice in the review?
I seem to be having a challenge with the including the get_average() method.
One thing I observed was that the .grades was printing out in string representation form and when I included repr in an attempt to debug it, I got a ‘NoneType’ error traceback. Here is code below: (can anyone spot the error?)
class Student(object):
attendance = {}
def init(self, name, year):
self.name = name
self.year = year
self.grades = list()
The last step in this exercise gives some additional things you could do with the classes’ you just created, and one of those things is:
“Write a Student method get_average() that returns the student’s average score.”
First here is the code I am working with, I have changed it slightly from what you end up with in the exercise for the sake of solving the “get_average” problem.
class Student:
def __init__(self):
self.grades = []
def add_grade(self, grade):
if type(grade) is Grade:
self.grades.append(grade)
def get_average(self):
return #???
class Grade:
def __init__(self, score):
self.score = score
S = Student()
grade_obj_1 = Grade(100)
grade_obj_2 = Grade(50)
S.add_grade(grade_obj_1)
S.add_grade(grade_obj_2)
At this point I have no idea how I could go about getting the average of a students grades, because they have been added to the grades list as Grade objects, so I cannot preform any kind of calculation on to return a value.
But the self.grades variable is just a list with 2 Grade objects in it.
print(S.grades)
Output:
[<__main__.Grade object at 0x7f150a301668>, <__main__.Grade object at 0x7f150a3016a0>]
And if I try to do any kind of calculation on these Grade objects I get an error
S.grades[0] + S.grades[1]
Output:
File "script.py", line 25, in <module>
S.grades[0] + S.grades[1]
TypeError: unsupported operand type(s) for +: 'Grade' and 'Grade'
I get the same error if I try to do the calculation in the get_average method in the Student Class.
Could you maybe provide an example of how I could preform calculations on these objects?
grades is a list containing Grade objects as you’ve mentioned. You need to access the property of the Grade object that contains the value. You are almost there with S.grades[0]. That is the first grade object. How do you access its property?
Hint
class Grade:
def __init__(self, score):
self.score = score
^^^^^
Thanks @midlindner,
This really did help, but it still took me a long time to figure out I was looking for S.grades[0].score
I am definitely going to need some more time to get a handle on classes.
Since we are instantiating a Grade class within the argument of the add_grade() method, it doesn’t get assigned as a referable instance except by accessing the grades instance variable (the list of grades).
pieter.add_grade(Grade(100))
def get_grades(self):
return [x.score for x in self.grades]