hnowak at cuci.nl
Sun Sep 2 10:57:24 CEST 2001
On 31 Aug 01, at 11:00, John Hunter wrote:
> >>>>> "Hans" == Hans Nowak <hnowak at cuci.nl> writes:
> Hans> Yes. You only need __getitem__:
> >>>> class Seq:
> Hans> def __init__(self, seq): self.seq = seq def
> Hans> __getitem__(self, index): return self.seq[index]
> >>>> s = Seq("cocoricoo") for c in s: print c,
> Hans> c o c o r i c o o
> Thanks for the reply. I think you also need to raise the IndexError
> exception as well, as Alex pointed out. I think your example relies
> on 'seq' to raise that exception for it. No?
Well, yes, because seq is supposed to be a sequence itself (or something that
emulates it), so we're counting on it that it eventually will raise IndexError
when the end of the sequence is reached. You can always explicitly raise it,
e.g. to restrict the number of items:
>>> class Seq:
def __init__(self, seq):
self.seq = seq
def __getitem__(self, index):
if index >= 10:
>>> s1 = Seq("abcdefghijklm")
>>> for c in s1: print c,
a b c d e f g h i j
> In my case, I am
> wrapping the c++ std::vector<type> as a python extension, so I have to
> raise that exception myself. I did implement __getitem__ but the 'in'
> loop never terminates, so now I have to figure out how to raise the right
> exception from C++.
Can't help you there... I don't know much about extensions in C++. :( Maybe
Alex Martelli does...?
--Hans Nowak (zephyrfalcon at hvision.nl)
You call me a masterless man. You are wrong. I am my own master.
May a stockbroker crush your Nissan Micra!
More information about the Python-list