i trying define list instance variable within class acting class variable.
class thing: def __init__(self, name, stuff): self.name = name self.dict = [] item in stuff: self.dict.append(item) def getname(self): return self.name def getlist(self): return self.dict def inc_datecnt(self,date): item in self.dict: if item.has_key(date): item[date] += 1 list = [] dates=['july1,2015', 'july2,2015', 'july3,2015'] datecnts = [] date in dates: datecnts.append({date : 0}) list.append(thing('a', datecnts)) list.append(thing('b', datecnts)) item in list: print "\n", item.getname() item.inc_datecnt('july1,2015') subitem in item.getlist(): print subitem when execute get:
a {'july1,2015': 1} {'july2,2015': 0} {'july3,2015': 0} b {'july1,2015': 2} {'july2,2015': 0} {'july3,2015': 0} i seem increment single class dictionary element july1,2015 when want (and expect) incrementing instance variable.
help
when passing datecnts list thing object's constructor, passing reference (and list mutable , dict mutable) , hence if make changes dict a thing object, reflect in b , since b has same reference. should try copy.deepcopy of datecnts , send a , b separately.
example -
import copy list.append(thing('a', copy.deepcopy(datecnts))) list.append(thing('b', copy.deepcopy(datecnts)))
Comments
Post a Comment