Add methods to string objects.

Roy Smith roy at
Thu Jun 30 14:22:07 CEST 2005

negroup at (Negroup) wrote:
> 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().

You can't quite do that, but you can get close.  You can define your own 
class which inherits from str, and then create objects of that class.  For 

class myString (str):
    def __init__ (self, value):
        self.value = value

    def plural (self):
        if self.value[-1] in "sz":
            return self.value + "es";
            return self.value + "s";

foo = myString("foo")
bar = myString("bar")
baz = myString("baz")

print foo.plural(), bar.plural(), baz.plural()  # my defined method
print foo.capitalize()                          # inherited from base class

More information about the Python-list mailing list