Object containing a list of objects.

MRAB python at mrabarnett.plus.com
Sat Aug 28 14:04:16 EDT 2010


On 28/08/2010 18:48, cocolombo wrote:
> 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 ?
>
When you write:

     class test(object):
         listOfScores = []

you're making 'listOfScores' an attribute of the class.

If you want it to be an attribute of an instance you should write:

     class test(object):
         def __init__(self):
             self.listOfScores = []



More information about the Python-list mailing list