By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,870 Members | 1,189 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,870 IT Pros & Developers. It's quick & easy.

Problem redefining __getitem__ for str subclass

P: n/a
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

Apr 22 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Hi!

Same result, with Python 2.5.1 on win-XP;
I have compassion with you.

--
@-salutations

Michel Claveau
Apr 22 '07 #2

P: n/a
<ts*****@gmail.comwrote:
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
Apr 22 '07 #3

P: n/a
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

Apr 22 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.