Steven D'Aprano wrote:
On Sun, 06 Dec 2009 22:47:48 -0800, Dr. Phillip M. Feldman wrote:
I wrote a handy-dandy function (see below) called "strip_pairs" for
stripping matching pairs of characters from the beginning and end of a
string. This function works, but I would like to be able to invoke it
as a string method rather than as a function. Is this possible?
Not exactly. You can subclass string and add such a method:
class MyString(str):
def strip_pairs(self, ...):
...
but then you have to convert every string to a MyString before you use
it. That way leads to madness.
Better to just use a function. Don't worry, you're allowed to mix
functional and OO code :)
Unlike certain other languages, Python is not designed around a fetish
for calling all functions as methods. s.func(arg) is immediately
translated to cls.func(s,arg) where cls is either the class of s or some
superclass thereof. Directly writing mod.func(s,arg), where mod is some
module, is just as good. Methods have three purposes: bundle several
related functions in a class-specific namespace; inheritance; mapping of
operations, like '+', to class-specific (special) methods. Modules are
an alernative namespace bundle.
Terry Jan Reedy
--
http://mail.python.org/mailman/listinfo/python-list