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

Martin von Loewis loewis at informatik.hu-berlin.de
Mon Oct 22 12:40:28 EDT 2001


"Andreas.Trawoeger" <Andreas.Trawoeger at wgkk.sozvers.at> writes:

>     def __getitem__(self,index):
>      return b2a_hex(self[index])
[...]
> 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__.

Just think of str being a class, and you attempting to write a super
call:

from binascii import b2a_hex

class octetstring(str):
    def __str__(self):
        return b2a_hex(self)
    def __getitem__(self,index):
     return b2a_hex(str.__getitem__(self,index))

o = octetstring('ABCD')
print "o   :",o
print "o[0]:",o[0]

Using the new "super" type, you can also write

    def __getitem__(self,index):
        return b2a_hex(super(octetstring,self).__getitem__(index))

HTH,
Martin



More information about the Python-list mailing list