class GradeBook: Define the GradeBook class. - def __init__(self): GradeBook con
ID: 3777578 • Letter: C
Question
class GradeBook: Define the GradeBook class.
- def __init__(self): GradeBook constructor. Create the only instance variable,
a list named grades, and initialize it to an empty list. This means that we
can only create an empty GradeBook and then add items to it later on.
- def __str__(self): returns a human-centric string representation. We'll
choose a multi-line representation (slightly unusual) that contains
"GradeBook:" on the first line, and then each successive line is a tab, the
str() representation of the next Grade in self.grades, and then a newline
each time. This means that the last character of the string is guaranteed to
be a newline (regardless of if we have zero or many Grade values).
- def __repr__(self): We will be lazy and tell this to just represent the
exact same thing as __str__. But don't cut-paste the code! Use this as the
entire body of this function: return str(self)
- def add_grade(self, grade): append the argument Grade to the end of
self.grades
- def average_by_kind(self, kind): Look through all stored Grade objects in
self.grades. All those that are the same kind as the kind parameter should be
averaged together (sum their percents and divide by the number of things of
that kind). If none of that kind exist, return None.
- def get_all_of(self, kind): create and return a list of references to each
Grade object in this GradeBook that is of that kind.
- def get_by_name(self, name): search through self.grades in order and return
the first Grade by the given name. If no such Grade value can be found (say,
name=="whatever"), then raise a GradingError with the message "no Grade
found named 'whatever'". (You can skip this exception-raising part and come
back to it).
"""
Explanation / Answer
class GradeError(Exception): def __init__(self, message): Exception.__init__(self, message) class GradeBook: def __init__(self): self.grades = [] def __str__(self): str = 'GradeBook:' for grade in self.grades: str += str(grade) + ' ' return str def __repr__(self): return str(self) def add_grade(self, grade): self.grades.append(grade) def average_by_kind(self, kind): count = 0 total = 0.0 for grade in self.grades: if grade.kind == kind: count += 1 total += grade.score if count == 0: return None else: return total / count def get_all_of(self, kind): same_kind_list = [] for grade in self.grades: if grade.kind == kind: same_kind_list.append(grade) return same_kind_list def get_by_name(self, name): for grade in self.grades: if grade.name == name: return grade raise GradeError('no Grade found named ' + name)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.