Problem redefining __getitem__ for str subclass

T

tsm8015

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
 
C

Carsten Haese

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
 
A

Alex Martelli

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top