Add methods to string objects.

Magnus Lycka lycka at carmen.se
Thu Jun 30 08:40:09 EDT 2005


Negroup wrote:
> 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
> my_module.my_function('mystring').
> 
> I was just asking if it is possible to "extend" string objects'
> behaviour so that it becomes possible to invoke something like
> 'anystring'.my_method().

The proper way is to extend the string type by subclassing it:

class S(str):
     def my_method(self):
         ...

Then you can do "S('anystring').my_method()" etc.

Example:

 >>> 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()
HW
 >>> print s.lowers()
elloorld

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 mailing list