[Tutor] Poorly understood error involving class inheritance
wescpy at gmail.com
Mon Oct 5 23:10:52 CEST 2009
> def __init__(self, time, mods=, dur=None, format='%1.2f'):
> The mods that were added to the first instance of oneStim also appear in the
> second, newly created instance!
> It appears that what is happening here is that the __init__() method is
> being parsed by the interpreter once at initial run, and at that time the
> statement "mods=" is being parsed, which means that the  object is being
> instantiated once there at the beginning. So every instantiation of class
> oneStim ends up sharing a reference to the same list object, instead of each
> one having its own.
> I fixed this by changing it to "mods=None" and then setting it in the body
> of the __init__ method. Works fine now.
> My question is, is this just a quirky misbehavior, or is there a principled
> reason why the code I have shown above only instantiates the empty list in
> the arguments once?
good eyes david,
you pretty much nailed it. what you describe is *exactly* what's going
on. you've run into one of the stumbling blocks that catch new and
seasoned Python programmers all the time: using a mutable object as a
default value... these objects are assigned early, hence the reason
why Python behaves the way it does. IOW, they are *not* assigned on a
per-call basis. (this is actually a popular interview question.) :-)
there is plenty of documentation online about this phenomenon, as it's
been with Python since the early days, or one or more of the other
tutors can post the appropriate links.
hope this helps!
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
More information about the Tutor