How is overloading __getitem__ in subclasses of str supposed to work in Pythton 2.2b1 ?

Walter Dörwald walter at livinglogic.de
Mon Oct 22 12:40:37 EDT 2001


Andreas.Trawoeger wrote:

> Hi!
> 
> A new Python 2.2 Beta version and another: Is this a bug or am I dumb
> question from myself (The last time I ran into the bug that overloading
> __str__ didn't work).
> Overloading __str__ does work fine in Python 2.2b1 (Thanks to Tim Peters
> for that). So my next adventure seams to be the __getitem__ method.
> 
> The following short and simple implementation ends in an endless loop:
> 
> from binascii import b2a_hex
> 
> class octetstring(str):
>     def __str__(self):
>         return b2a_hex(self)
>     def __getitem__(self,index):
>      return b2a_hex(self[index])

> 
> o = octetstring('ABCD')
> print "o   :",o
> print "o[0]:",o[0]
> 
> Well this isn't a surprise because I'm using the [ ] method in __getitem__
> which implements [ ].
> But I have no clue how I could write an different implementation for
> __getitem__.



How about the following:
    def __getitem__(self,index):
       return b2a_hex(str.__getitem__(self, index))

Bye,
    Walter Dörwald





More information about the Python-list mailing list