for item in some_class_object...

Chuck Esterbrook echuck at mindspring.com
Fri Apr 14 18:48:27 EDT 2000


Ben Wolfson wrote:

> What special methods should I define for a class if I want to support
> a for item in ... syntax for it?
>
> --
> Barnabas T. Rumjuggler al-Mumit
>
> Further-more, I have long since put the finishing touches on my own
> official obituary, a 350-page tale of heart-rending loss which
> details, among other things: my meteoric rise from Onion stringer to
> editor to publisher; my assassination at the hands of lady-actress
> Ethel Barrymore's jealous suitors; the thousand days of mourning which
> followed my death, during which a cold rain fell constantly, no bird
> sang, and children were born antlered and hooved; ...
>  -- T. Herman Zweibel

I believe that would be __getitem__ which needs to raise an IndexError when the buck stops short.

class X:
    def __getitem__(self, index):
        if index>=0 and index<10:
            return index
        else:
            raise IndexError


-Chuck




More information about the Python-list mailing list