# -*- encoding: utf-8 -*-
import collections
'''
第22条: 尽量用辅助类来维护程序的状态,而不要用字典
关键:
1 动态
含义:指这些保存的信息
建议:用来保存程序状态的数据结构如果复杂,应该拆分为类
2 把嵌套结构重构为类
collections模块的namedtuple(具名元组)
可以定义出不可变的数据类
定义: collections.namedtuple(元组名称,(属性名称1, 属性名称2, ...,属性名称N))
样例:
grade = collections.namedtuple('Grade', ('score', 'weight'))
缺点: namedtuple无法指定各个参数的默认值,可能用类比较号
3 总结
不要使用嵌套字典,不要使用长元组
简单不可变数据可以用namedtuple
字典复杂需要拆分为辅助类
参考:
Effectiv Python 编写高质量Python代码的59个有效方法
'''
Grade = collections.namedtuple('Grade', ('score', 'weight'))
class MySubject(object):
def __init__(self):
self.grades = []
def setGrade(self, score, weight):
self.grades.append(Grade(score, weight))
def getAverageGrade(self):
total, totalWeight = 0, 0
for grade in self.grades:
total += grade.score * grade.weight
totalWeight += grade.weight
return total / totalWeight
class MyStudent(object):
def __init__(self):
self.subjects = {}
def getSubject(self, subjectName):
if subjectName not in self.subjects:
self.subjects[subjectName] = MySubject()
return self.subjects[subjectName]
def getAverageGrade(self):
total, count = 0, 0
for subject in self.subjects.values():
total += subject.getAverageGrade()
count += 1
return total / count
class GradeBook(object):
def __init__(self):
self.students = {}
def getStudent(self, studentName):
if studentName not in self.students:
self.students[studentName] = MyStudent()
return self.students[studentName]
def process():
book = GradeBook()
chen = book.getStudent('chen')
math = chen.getSubject('Math')
math.setGrade(80, 0.1)
print chen.getAverageGrade()
if __name__ == "__main__":
process()