Saturday 15 June 2013

python - Function won't sucessfully loop over class instances unless contents entered manually in iPython console -



python - Function won't sucessfully loop over class instances unless contents entered manually in iPython console -

this uses similar sort of registry this question asked. within class, have registry (in form of list time) of instances of class. instance initialised coordinates, these changed user uses program. have made function resets these coordinates (simplified version)

class foobar: _registry = [] def __init__(self, position=[0,0,0], direction=[0,0,1]): self._pos = position # can alter later self._pos0 = position # stored static re-create of initial position self._dir = direction self._dir0 = direction # stored initial direction self._registry.append(self) # adds instance registry ... def remove(self): foobar._registry.remove(self) # removes instance registry def reset(self): self.remove() foobar.__init__(self, self._pos0, self._dir0) # re-initialises instance starting parameters ... def reset_all(): # note: outside of foobar item in foobar._registry: item.reset()

now, works if do

>>> = foobar([0,0,0], [0,0,1]) >>> a.do_something_that_adds_more_pos_&_dir_vectors() >>> b = foobar(... # same sort of thing. c, d etc >>> a.reset() >>> b.reset() >>> c.reset() >>> d.reset()

those reset fine. if come in ipython console

>>> item in foobar._registry: ... item.reset()

all objects reset fine. if reset_all() instead, find of instances reset, whilst others don't. if maintain doing reset_all() have reset, not in 1 go. what's going on!?

extra info: append position , direction vectors these objects. plot paths dictated vectors. if seek reset_all() , seek plot them again, of them reset , no longer show on plot (as expected), half still show up.

you're indirectly mutating foobar._registry iterate on it. illegal, , can in theory lead working fine reformatting hard drive, in practice means end skipping on of values.

the simplest alter iterate on copy: for item in foobar._registry[:]:

python class object

No comments:

Post a Comment