Problem redefining __getitem__ for str subclass

Alex Martelli aleax at mac.com
Sun Apr 22 00:56:13 EDT 2007


<tsm8015 at gmail.com> wrote:

> I do not think I am understanding how to redefine the getitem function
> for string. Why does the following not work:
> 
> class NStr(str):
>     def __getitem__(self,idx):
>         print "NStr:getitem",idx,type(idx)
>         return str.__getitem__(self,idx)
> 
> s=NStr("abcde")
> 
> print s[1]
> print s[1:4:2]
> print s[1:2]
> 
> if I run this program (python 2.5; Mac OSX) i get:
> 
> $ python strProb.py
> NStr:getitem 1 <type 'int'>
> b
> NStr:getitem slice(1, 4, 2) <type 'slice'>
> bd
> b
> 
> ie the last statement (s[1:2]) with a simple slice does not call the
> new __getitem__???? What am I missing.

For backwards compatibility, slicing without a step on some ancient
built-in types (including strings, but also lists) goes to __getslice__
(an otherwise obsolete method) instead of __getitem__.  Simply, override
__getslice__ by properly delegating from it to __getitem__.


Alex



More information about the Python-list mailing list