[Tutor] OO Python: How to change attributes of just one object in a list
Andrei Kulakov
ak@silmarill.org
Mon, 20 May 2002 02:54:13 -0400
On Mon, May 20, 2002 at 02:34:13AM -0400, Geoffrey Bays wrote:
> I am trying to write an OO program in Python to keep track of students in
> classes of mine. Unfortunately, the changeGrade() method in class Course
> changes all of the students' grades on the same test to the same grade.
> I have determined that the for and if clauses work correctly, and have
> tried defining __eq__() and __del__ in the Student class, writing a
> changeGrade method in class Student, etc, but none of this does any good. I
> just want to push student objects onto the studentList and change their
> grades individually.
> Any help would be much appreciated.
>
> class Student:
> def __init__(self, name):
> self.name = name
> self.record = {}
>
> def display(self):
> print self.name, '\n'
> for item in self.record.keys(): print item, '\t', self.record[item],
> print '\n'
>
> class Course:
> def __init__(self,name):
> self.name = name
> self.tests = {}
> self.design()
> self.studentList = []
>
> def design(self):
> s = raw_input('Enter graded items for the course separated by commas:\
> test = s.split(",")
> for X in test:
> self.tests[X] = -1
>
> def display(self):
> print c.name," "
> for test in c.tests.keys(): print test,": ",c.tests[test],
> print '\n'
>
> def addStudent(self,name):
> s = Student(name)
> s.record = self.tests
> self.studentList.append(s)
>
> def displayCourse(self):
> for i in range(len(self.studentList)):
> self.studentList[i].display()
>
> def changeGrade(self,studName,test,score):
> boolean = 0
> for i in range(len(self.studentList)):
> if(self.studentList[i].name == studName ):
> self.studentList[i].record[test] = score //This is the line that
> changes all the students grades, not just the one
> boolean = 1
> if (boolean == 0):
> print "No student of that name found."
>
>
>
>
This does not show up correctly formatted here.. could you please
repost? Also add some test code.
Wouldn't it be better though to store students in a dictionarary
with names as keys, instead of a list?
Then you can changeGrade as:
students[name].record[test] = score
Actually, it *should* be in Student class:
self.record[test] = score
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org