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

if __name__ == '__main__':

   s = mystr('one two <three> four')
   print s
   print type(s)
   b,r = s.between('<', '>')
   print b
   print r
   print type(b)
   print type(r)
   c = s.replace('three', 'five')
   print c
   print type(c)


when I ran it I get:

one two <three> four
<class '__main__.mystr'>
three>
 four
<type 'str'>
<type 'str'>
one two <five> four
<class '__main__.mystr'>


I guess that if I had redefined the slice method even 'between' would have returned <class '__main__.mystr'>

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

thanks

--
bye
!(!1|1)
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to