Skip to content

Instantly share code, notes, and snippets.

@sangheestyle
Created January 30, 2017 05:16
Show Gist options
  • Save sangheestyle/2939ef6d642ac0f62b05d83c721e54da to your computer and use it in GitHub Desktop.
Save sangheestyle/2939ef6d642ac0f62b05d83c721e54da to your computer and use it in GitHub Desktop.
Item 22: Prefer Helper Classes Over Bookkeeping with Dictionaries and Tuples from Effective Python written by Brett Slatkin
# This code is from
# Item 22: Prefer Helper Classes Over Bookkeeping with
# Dictionaries and Tuples
# from Effective Python written by Brett Slatkin
# 2015
import collections
Grade = collections.namedtuple('Grade', ('score', 'weight'))
class Subject(object):
def __init__(self):
self._grades = []
def report_grade(self, score, weight):
self._grades.append(Grade(score, weight))
def average_grade(self):
total, total_weight = 0, 0
for grade in self._grades:
total += grade.score * grade.weight
total_weight += grade.weight
return total / total_weight
class Subject(object):
def __init__(self):
self._grades = []
def report_grade(self, score, weight):
self._grades.append(Grade(score, weight))
def average_grade(self):
total, total_weight = 0, 0
for grade in self._grades:
total += grade.score * grade.weight
total_weight += grade.weight
return total / total_weight
class Student(object):
def __init__(self):
self._subjects = {}
def subject(self, name):
if name not in self._subjects:
self._subjects[name] = Subject()
return self._subjects[name]
def average_grade(self):
total, count = 0, 0
for subject in self._subjects.values():
total += subject.average_grade()
count += 1
return total / count
class Gradebook(object):
def __init__(self):
self._students = {}
def student(self, name):
if name not in self._students:
self._students[name] = Student()
return self._students[name]
book = Gradebook()
albert = book.student('Albert Einstein')
math = albert.subject('Math')
math.report_grade(80, 0.10)
print(albert.average_grade())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment