String Methods Don't Change ID?
sholden at holdenweb.com
Tue Jan 28 15:15:35 CET 2003
"Kamilche" <klachemin at home.com> wrote in message
news:889cbba0.0301271948.3c8843fc at posting.google.com...
> 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 nothing that special about strings, they are simply objects with a
particular property called "immutability". That just means they can't be
changed once they are created.
However, you seem to be suffering from the illusion that all methods are
about modifying objects. They aren't. Methods are simply calls to specific
pieces of functionality, which relate to the type or class of the object.
In your logon example, it's quite possible that the person.logon() method
would create a new object, a loggedOnPerson, which contained a reference to
the original person. It's all a matter of how you choose to implement your
functionality. Strings being immutable, of course, nothing can change them.
Back in "the old days" before strings spruoted the methods we've come to
know and love, you used to have to write
a='what is your favorite color?'
a = string.capitalize(a)
This made it more obvious that you had to bind the name "a" to a new string,
but it was rather less intuitive (to me, at least). If you can think of some
way to express your misunderstanding that might save other newcomers from
the same problems it might be helpful (for the other newcomers) if you were
to try to do so.
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/pwp/
Bring your musical instrument to PyCon! http://www.python.org/pycon/
More information about the Python-list