Object containing a list of objects.

2010-08-28 Thread cocolombo
Hello.

I am putting objects (test) into a container object (tests) and the
test object is also a container for a another list of object
(scores).

Problem is that all instances of class tests have the same value.

To illustrate:

class score(object):
val = 0
def __init__(self, val):
self.val = val
def __str__(self):
return str(self.val) + "\n"

class test(object):
listOfScores = []
def __str__(self):
ret = ""
for s in self.listOfScores:
ret += str(s)
return ret

class tests(object):
listOfTest = []
def __str__(self):
ret = ""
for t in self.listOfTest:
ret += str(t)
return ret


Now I run the script
:
==
score1 = score(10)
score2 = score(20)
score3 = score(30)
score4 = score(40)

test1 = test()
test2 = test()


test1.listOfScores.append(score1)
test1.listOfScores.append(score2)
test2.listOfScores.append(score3)
test2.listOfScores.append(score4)

theTests = tests()
theTests.listOfTest.append(test1)
theTests.listOfTest.append(test2)

print theTests.listOfTest[0]
print theTests.listOfTest[1]

==

This is the data structure I am EXPECTING:

theTests
 test1
 ---score1=10
 ---score2=20
 test2
 ---score3=30
 ---score4=40


But what I get is this:

theTests
test1
  ---score1=10
  ---score2=20
  ---score3=30
  ---score4=40
 test2
  ---score1=10
  ---score2=20
  ---score3=30
  ---score4=40

What is wrong ?

Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object containing a list of objects.

2010-08-28 Thread cocolombo
Thanks MRAB and Peter Otten that solved the problem.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object containing a list of objects.

2010-08-28 Thread cocolombo
Chris I take good notice of your comments and suggestions. Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list