0

So I have a list of objects in which I have a list. The list has common strings and is supposed to have some specific strings for every object depending on another variable.

class test: 
   strings = []
   name = None

Then I'm creating a list of objects

objects = []
i = 0
while i < 2 :
   o = test()
   o.name = "Object " + str(i)
   objects.append(o)
   i += 1

Then I'm adding general strings for both objects in the list

test.strings.append("String 1")
test.strings.append("String 1")

What I need is for each object to have a specific string after those, so I tried

test.append("testing")
for element in objects :
   print element.strings[ len(element.strings) - 1 ]
   element.strings[ len(element.strings) - 1 ] = element.name
   print element.strings[ len(element.strings) - 1 ]

The output I'm getting is

testing
Object 0
Object 0
Object 1

And when I try to access element.strings where that string is it always is the last modification.

I tried appending individually, also, instead of doing the test.append before the for, but it added elements to every object. Is there a way to do what I'm trying to do?

Edit against duplicate: What the other question is asking is how to have independent data with no shared information. What I want is shared information with a few instances of specific data.

peterh
  • 11,875
  • 18
  • 85
  • 108
Gabriel
  • 1
  • 1
  • Please show real code. That would fail with `NoneType object has no attribute 'append'`, because `strings` is None not a list. – Daniel Roseman Sep 30 '16 at 12:47
  • Why don't you use `pdb` to debug and check values at every step? – Aashish P Sep 30 '16 at 12:48
  • I'm sorry, I modified it accordingly. strings = [] – Gabriel Sep 30 '16 at 12:49
  • I guess this is what you want: http://pastebin.com/0u1bBH2j (I don't agree that this question is a duplicate, I have to use the comment field as the question is closed at the moment) – user2436850 Sep 30 '16 at 13:18
  • Yes. Thanks a lot. I will look into this, I did a workaround using dictionaries with the key being the position in which the specific string would be in the general strings array. – Gabriel Sep 30 '16 at 14:55

0 Answers0