0

I am trying to save events for different items as they occur. However, when I go to get the results, only 1 event's occurrences are printing and I am not sure why.

import time
from datetime import datetime as DT

class test:
    event = {}

    def __init__(self,pin,name):
        self.name = name
        self.pin = pin

    def somethingHappens(self,what):
        self.event[what] = DT.now()

    def printResults(self):
        sortKeys = (self.event).keys()
        sortKeys.sort()
        print self.name
        for k in sortKeys:
            value = repr(k) + "," + repr(self.event[k])
            print value

objList = []
objects = {'book':3, 'bottle':5, 'pen':8}
nameList = objects.values()
numList = objects.keys()
for i in range(len(nameList)):
    objList.append(test(nameList[i],numList[i]))

x = 0
while x <= 1:
    objList[x].somethingHappens('Start')
    time.sleep(.5)
    objList[x].somethingHappens('End')
    time.sleep(1)
    x += 1

x = 0
while x <= 2:
    objList[x].printResults()
    x += 1

with results:

pen
'End',datetime.datetime(2015, 5, 22, 9, 39, 10, 947000)
'Start',datetime.datetime(2015, 5, 22, 9, 39, 10, 432000)
book
'End',datetime.datetime(2015, 5, 22, 9, 39, 10, 947000)
'Start',datetime.datetime(2015, 5, 22, 9, 39, 10, 432000)
bottle
'End',datetime.datetime(2015, 5, 22, 9, 39, 10, 947000)
'Start',datetime.datetime(2015, 5, 22, 9, 39, 10, 432000)

Hopefully it is something simple.

Matt
  • 41
  • 1
  • 6
  • If I print the results during the first while loop, then the results come out correctly. – Matt May 22 '15 at 16:47
  • `event` is a class attribute, when it should be an instance attribute. – chepner May 22 '15 at 16:49
  • 1
    Given that you do have instance attributes, why on earth did you make `event` a class attribute? Put `self.event = {}` into `__init__`. – jonrsharpe May 22 '15 at 16:50
  • I don't think that's a good duplicate; there are no default function arguments in this question. – chepner May 22 '15 at 16:52
  • @chepner you're right, sorry; I meant this one: http://stackoverflow.com/questions/1680528/how-do-i-avoid-having-python-class-data-shared-among-instances. Could you do the honours? – jonrsharpe May 22 '15 at 16:53

0 Answers0