Problem redefining __getitem__ for str subclass

Carsten Haese carsten at uniqsys.com
Sun Apr 22 00:55:39 EDT 2007


On 21 Apr 2007 20:36:13 -0700, tsm8015 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.

You're overriding __getitem__ just fine, but if your object has a __getslice__
method, __getslice__ will be called instead of __getitem__ to fetch simple
slices. Since you are deriving from str which does implement __getslice__,
you'll need to override __getslice__, too.

-Carsten




More information about the Python-list mailing list