Class Or Object Instead Of Dictionaries In Python 2
I normally use nested dictionaries, but I'd like to move into classes and objects. I have a list of home work grades that look like: assignment_name assignment_subject student_name
Solution 1:
classstudent:
def__init__(self, student_name):
self.name = student_name
classhomework:
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
@classmethoddefnew_hw(cls, line):
return cls(line[0],line[1],line[2],line[3])
@classmethoddefget_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)
What you need to understand is "How to design Object-Orientedly?". The above code, may not be the best of designs, hence, try this to learn where to start. How do I design a class in Python?
Solution 2:
Don't do that.
Just make a Homework
class and a Student
class.
You can create a list of Homework
classes and then just pass the students that are part of each "homework" to their respective object.
For example:
classHomework(object):def_init_(self, name, subject):
self.assignment_name = name
self.assignment_subject = name
self.students = []
defadd_student(self, student):
self.students.append(student)
classStudent(object):def_init_(self, student_name):
self.student_name = student_name
You can expand from there.
What I would really do is have a list of Class
es that each have homework.
And each student could be in multiple Classes, etc, but it really all up to you
Have fun with it!
Post a Comment for "Class Or Object Instead Of Dictionaries In Python 2"