Problem redefining __getitem__ for str subclass

tsm8015 at gmail.com tsm8015 at gmail.com
Sat Apr 21 23:36:13 EDT 2007


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.

Thanks

tom




More information about the Python-list mailing list