class or object instead of dictionaries in Python 2
我通常使用嵌套字典,但我想转移到类和对象中。我有一份家庭工作成绩清单,如下所示:
1 | assignment_name assignment_subject student_name due_date grade grade_pct rank |
我想做一个能容纳所有学生的物体,每个学生能容纳他们所有的作业细节。我的字典看起来像:
1 | homeworks['student_name']['assignment_name'] = {'assignment_subject': 'math', 'due_date': '11/12/13', 'grade': 15, 'grade_pct': 15/20.0, 'rank': 'B'} |
号
这应该是一个类中的一个类吗?
1 2 3 4 5 6 7 8 9 10 11 12 | class Homeworks(object): def _init_(self): self.students class student(object): def _init_(self,student_name): self.student_name = student_name def add_assignment(line): student.assignment_name = line[0] student.assignment_subject = line[1] student.grade = line[4] |
我知道这不对。我不知道我是否在正确的轨道上。我需要能够获得一个学生的成绩。(
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class student: def __init__(self, student_name): self.name = student_name class homework: def __init__(self,student_name,assignment_name,assignment_subject,grade): self.student = student(student_name) self.assignment_name = assignment_name self.assignment_subject = assignment_subject self.grade = grade @classmethod def new_hw(cls, line): return cls(line[0],line[1],line[2],line[3]) @classmethod def get_all_grades(cls, student_name, homework_list): return [ x.grade for x in homework_list if student_name is x.student.name] lines = [["abc","a","b","A"],["abc","c","d","B"],["ebc","c","d","B"]] hw_list = [homework.new_hw(line) for line in lines] print homework.get_all_grades("abc",hw_list) |
号
你需要理解的是"如何面向对象设计?".上面的代码,可能不是最好的设计,因此,试着学习从哪里开始。如何在Python中设计类?
别那么做。
只需创建一个
您可以创建一个
例如:
1 2 3 4 5 6 7 8 9 10 11 12 | class Homework(object): def _init_(self, name, subject): self.assignment_name = name self.assignment_subject = name self.students = [] def add_student(self, student): self.students.append(student) class Student(object): def _init_(self, student_name): self.student_name = student_name |
你可以从那里扩展。
我真正要做的是列出每个人都有家庭作业的
每个学生都可以上多个班等等,但这完全取决于你。
玩得开心!