I’ve got this code:
def __parse(self):
for line in self.lines:
r = Record(line)
self.records[len(self.records):] = [r]
print self.records[len(self.records)-1].getValue() # Works fine!
print self.record[0].getValue() # Gives the same as
print self.record[1].getValue() # as
# ... and so on ...
print self.record[len(self.record)-1].getValue()
Now what it should do is making records out of lines of text. But when I access those list after the for-loop has completed all records give the same results for methods I call on them. When I access a record within the for-loop right after it was appended it’s the right one so the Record init can’t be fault. No, it’s absolutely sure that the lines I put in are different! Has anyone an idea why this happens? Help would be very appreciated!
Ahue, you have mutable objects in the shared class namespace — a very common misconception when starting out with python. Move the initialization of
records = []inCsvSetinto its__init__function, and moverecord = {}intoRecord__init__function. Should look like the following:When you declare a mutable variable in the class area, it is shared among all instances of those classes, not created for each instance. By moving the initialization into an instance method (
__init__in this case), you are creating new mutable stores for each instance, which is what you intended.