Jeremy Winters wrote: > class SegmentValue: > def > __init__(self,seg=[0,0,0,0,0,0],value=0,description=""): > self.segment=seg > self.value=value > self.description=description > > #that's my class! note the default of a 6 item list > for the seg parameter... which is then bound(?) to the > segment attribute of the instance... > > now here's the session I just did > >>>> from SegmentValue import * >>>> a=SegmentValue([1,2,3,4,5,6],22,"segment a") >>>> b=SegmentValue() >>>> c=SegmentValue() >>>> b.segment[0]=1 >>>> b.segment > [1, 0, 0, 0, 0, 0] >>>> c.segment > [1, 0, 0, 0, 0, 0] >>>> a.segment > [1, 2, 3, 4, 5, 6] > > so... what I'm seeing here is that when I explicitly > set seg during instantiation... it creates a unique > sequence that can be manipulated without affecting > other instances... but if I instantiate using the > default... it seems to refer back to the default when > maniuplating the segment attribute. > > in a continuation of the session... > >>>> d=SegmentValue() >>>> d.segment > [1, 0, 0, 0, 0, 0] > > ...you'll note that any new instances now refer to the > *modified default sequence*. > > what is going on here? how do I instantiate without > explicitly defining a new sequence each time? or is > this even possible? > > thanks in advance, > jeremy > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com
It trips up almost everyone at first. You should not use a list (mutable) as a default keyword argument. >From Python Language Reference Manual by Guido van Rossum and Fred L. Drake, Jr.: 6.3.4 Calls <snip> Default values are calculated, once, when the function is defined; thus, a mutable object such as a list or dictionary used as default value will be shared by all calls that don't specify an argument value for the corresponding slot; this should usually be avoided. <end snip> Change to something like: __init__(self,seg=None,value=0,description=""): self.segment=seg or [0,0,0,0,0,0] self.value=value self.description=description -Larry Bates -- http://mail.python.org/mailman/listinfo/python-list