__getitem__ AttributeError

Alex Martelli aleaxit at yahoo.com
Wed Nov 1 15:36:07 EST 2000


"Jeroen Valcke" <jeroen at valcke.com> wrote in message
news:3A0066C5.527FB5D9 at valcke.com...
>
> Alex Martelli wrote:
> <snip>
> > and class Slidelist does not define a __getitem__ method,
> > so its instances cannot be indexed with [] nor iterated on
    [snip]
> > class Slidelist:
    [snip]
> >     def __getitem__(self, index):
    [snip]
> Yep, this seems to resolve the problem. Thanks

You're welcome.

> I'm a bit clueless though, how can I know when to define this class? Is
> this overloading?

Yes, defining the __getitem__ method of a class is in some
sense 'overloading' -- it's an indirect way Python offers you
to overload the foo[something] syntax ('indexing') when foo
is an instance of your class.  (And as a nice side effect, this
also analogously overloads 'for x in foo', 'if x in foo' ...).

You should give a class a __getitem__ method if you want
its instances to be usable as "indexable containers of items",
and in particular (with integer indices from 0 to N-1...) as
"sequences" (on which 'for' can iterate).

It's your design decision, whether you DO want instances
of a given class of yours to be usable this way.


Alex






More information about the Python-list mailing list