Re: Add methods to string objects.



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).
.



Relevant Pages

  • Re: importing a method
    ... > def meth1: ... > I want to allow the user to write a python module that declares a ... > method of the soandso object. ... print "bar() got arguments:", ...
    (comp.lang.python)
  • Re: Calling python functions from C
    ... e.g. my Python module: ... def plus: ... C:\devel\embed>runfunc arith plus 1 2 ... C:\devel\embed>runfunc arith times 1 2 ...
    (comp.lang.python)
  • pyrex functions to replace a method (Re: replace a method in class: how?)
    ... I feel a little sheepish for not having caught that I have to replace it in the class, not the instance, but I have found a very similar problem trying to replace a method using a function defined in pyrex. ... def update1: ... This.update2=module_py.python_update # replace the method from a python module ...
    (comp.lang.python)
  • Re: Is there such an idiom?
    ... def ii_set: ... for lst in lsts: ... From what I recently read here in another thread, in python 2.3 sets were implemented as a python module using dictionaries, and in 2.4 it was written in C code based on the dictionary C code. ...
    (comp.lang.python)