[Tutor] OO Python: How to change attributes of just one object in alist

Paul Sidorsky paulsid@shaw.ca
Mon, 20 May 2002 01:22:15 -0600


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.
[snip]

> def addStudent(self,name):
>     s = Student(name)
>     s.record = self.tests
>     self.studentList.append(s)

The middle line above is the problem.  It makes each student's record
refer to the course's tests dictionary.  Since all of the students'
records refer to the same object, a change to one student is reflected
in all of the others.  Making a copy of self.tests will solve your
problem.  I don't know the standard idiom to copy a dictionary so I
would probably just do it manually.

On another note, your design looks shaky and will probably become
increasingly difficult to manage as the program grows.  I suggest
rethinking your approach.  I don't know too much about Design Patterns
but I highly suspect there's one that will fit your situation quite
well; try checking some DP sites.  

Failing that you can always ask us for help.  :-)  I haven't thought
about it too much but FWIW I would probably give each student an ID
number and store them all in a dictionary with the ID as the key.  Then
each course needs only to store a list of ID numbers of students
enrolled in that course.  I'd also use IDs for courses.  For things like
grades I might then use a nested dictionary stored inside each student,
and access it like this:  student.grades[courseid][test].  This might
sound complicated but it's not really and I think it'll be quite a bit
easier to manage.  I can elaborate if you'd like.

BTW in the future for your own sake and ours please try to paste your
code directly into your message, without editing.  The indentation got
all messed up and that took a while to sort through.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/