Strings & methods

Michael Hudson mwh21 at cam.ac.uk
Thu Feb 24 14:42:28 EST 2000


Def P <def-p at usa.net> writes:

> OK, here's a stupid question... Why do strings have methods in 1.6?
> 
> Before everybody flames me, let me explain the reasons of my
> confusion. My trusty old OOP textbooks say, that object orientation
> is about encapsulating data in objects, to access them through
> methods. The methods (should) ensure that the data are changed
> correctly. This makes sense for Python classes and mutable objects
> like lists and dicts. However, since strings are immutable (I'm
> assuming they still are in 1.6), those methods won't change the
> string itself at all; they will rather act like functions glued to
> the object. To the uninitiated, this may look like the old string
> functions have been changed to methods in unnatural ways, and indeed
> it sometimes leads to peculiar constructs like "
> ".join(list_of_strings). (I know this construct has been explained
> in the newsgroup, and while the reasons for choosing this way are
> understandable, intuitive it is not.)
> 
> Don't get me wrong, I'm not saying string methods are a bad idea,
> I'm just wondering. There is probably a good reason for this, but I
> haven't managed to find it so far. My next question is, why have
> strings grown methods, but integers, floats, tuples haven't?

Well, I think it's basically down to the fact that Python is designed
not according to ivory-tower philosophical rules, but observation of
what people do, and what can be done to make their lives easier.
Besides, I don't think OO is *all* about mutation of state - that
would leave functional OO languages like ocaml in rather an odd
position.  Would you really rather write:

newstr = str.copy()
newstr.convert_to_upper_case()
return func(newstr)

than

return func(str.upper())

?

pragmatically-y'rs
Michael

-- 
very few people approach me in real life and insist on proving they are
drooling idiots.                         -- Erik Naggum, comp.lang.lisp



More information about the Python-list mailing list