Add methods to string objects.
lycka at carmen.se
Thu Jun 30 14:40:09 CEST 2005
> Hi all.
> I'm writing a simple Python module containing functions to process
> strings in various ways. Actually it works importing the module that
> contains the function I'm interested in, and calling
> I was just asking if it is possible to "extend" string objects'
> behaviour so that it becomes possible to invoke something like
The proper way is to extend the string type by subclassing it:
Then you can do "S('anystring').my_method()" etc.
>>> class S(str):
... def lowers(self):
... return filter(lambda x:x!=x.upper(), self)
... def uppers(self):
... return filter(lambda x:x!=x.lower(), self)
>>> s = S('Hello World!')
>>> print s.uppers()
>>> print s.lowers()
This means that your additional behaviour isn't available to
plain string literals. You need to instanciate S objects. This
is much less confusing for other programmers who read your code
(or for yourself when you read it a few years from now).
More information about the Python-list