String Methods Don't Change ID?

Peter Hansen peter at engcorp.com
Tue Jan 28 09:31:58 EST 2003


Kamilche wrote:
> 
> Peter Hansen <peter at engcorp.com> wrote in message news:<3E35A9B3.87D605DC at engcorp.com>...
> >
> > Finish up your example by typing "quest" again:
> >
> > >>> quest
> > 'what is your favorite color?'
> >
> > Hmm.... neither very centered, nor capitalized, is it?  So it hasn't
> > been modified. ;-)
> >
> 
> Heheheh, I get it now, thanks. :-)
> 
> Calling a method on a string SEEMS like it should modify the original,
> not create a new one, but I guess strings are 'special' all the way
> around.  To me, it's kinda like saying 'person.logon(logonid,
> password)' creating a new person object and logging them on, while
> leaving the original person untouched.

There's actually a very good reason to design classes with the property
of immutability, so that you *don't* get that kind of effect.  Otherwise,
when you have multiple references to an object and the owner of one of
those references changes the object, all the other owners see the change
(an effect called aliasing).  Only *sometimes* is this the behaviour you
want, so don't assume it should always work this way.

-Peter




More information about the Python-list mailing list