zoukankan      html  css  js  c++  java
  • 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())
    

    请相信自己

    当我们迷茫,懒惰,退缩的时候 我们会格外的相信命运 相信一切都是命中注定

    而当我们努力拼搏,积极向上时 我们会格外的相信自己

    所以命运是什么呢? 它是如果你习惯它 那它就会一直左右你

    如果你想挣脱它 那它就成为你的阻碍 可如果你打破了它 那它就是你人生的垫脚石!


    如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!

  • 相关阅读:
    程序运行bug查看
    c# webbrowser 的html调用js出错
    c# dll使用注意
    支持ie的时间控件 html
    sql 条件插入
    软件自动更新原理
    c# 数组不能直接=,需要clone
    打包成exe程序
    逆袭大学
    Heritage from father
  • 原文地址:https://www.cnblogs.com/suguangti/p/15203613.html
Copyright © 2011-2022 走看看