Loading

Effective Python Ver2.0_StudyNotes_使用类体系去解决多层嵌套问题

要点:
不要在字典里嵌套字典、长元组,以及用其他内置类型构造的复杂结构
namedtuple能够实现出轻量级的容器,以存放不可变的数据,而且将来可以灵活地转化为普通的类
如果发现用字典来维护内部状态的那些代码已经越来越复杂了,那么就应该考虑改用多个类来实现

直接上代码

from collections import namedtuple, defaultdict
Grade = namedtuple('Grade', ('score', 'weight'))

class Subject:
    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:
    def __init__(self):
        self._subjects = defaultdict(Subject)

    def get_subject(self, name):
        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:
    def __init__(self):
        self._students = defaultdict(Student)

    def get_student(self, name):
        return self._students[name]


if __name__ == '__main__':
    book = Gradebook()
    albert = book.get_student('Albert Einstein')
    math = albert.get_subject('Math')
    math.report_grade(75, 0.05)
    math.report_grade(65, 0.15)
    math.report_grade(70, 0.80)
    gym = albert.get_subject('Gym')
    gym.report_grade(100, 0.40)
    gym.report_grade(85, 0.60)
    print(albert.average_grade())
posted @ 2021-08-29 21:02  MrSu  阅读(45)  评论(0编辑  收藏  举报