subclassing str

Chris Rebert clp2 at rebertia.com
Sun Nov 7 01:41:44 EST 2010


On Sat, Nov 6, 2010 at 10:43 PM, not1xor1 (Alessandro) <"
"@libero.it> wrote:
> Hi,
>
> I'd like to know what is the best way to subclass str
> I need to add some new methods and that each method (both new and str ones)
> return my new type
>
> For instance I've seen I can do:
>
> class mystr(str):
>
>   def between(self, start, end):
>      i = self.index(start) + len(start)
>      j = self.index(end, i) + len(end)
>      return self[i:j], self[j:]
>
>   def replace(self, old, new='', count=-1):
>      return mystr(str.replace(self, old, new, count))
>
<snip>
> I wonder if I have to redefine all methods one by one or if there is a sort
> of hook to intercept all methods calls and just change the return type

You could subclass UserString instead of str; all of UserString's
methods seem to ensure that instances of the subclass rather than just
plain strs or UserStrings are returned. See
http://docs.python.org/library/userdict.html#UserString.UserString

But you should also consider whether your additions absolutely *must*
be methods. Merely instead defining some functions that take strings
as parameters is obviously a simpler, and probably more performant,
approach.

If you insist on subclassing str, there's no such hook; you'll have to
override all the methods yourself.*

Cheers,
Chris
--
*Well, you could override only the __special__ methods and
__getattribute__(), or use metaprogramming, but at that point you
might as well go the UserString route if possible.
http://blog.rebertia.com



More information about the Python-list mailing list