defining __getitem__

Clemens Hintze c.hintze at
Thu Apr 27 07:30:15 CEST 2000

"Gang" Gang Seong has written:
   Gang> I'd like to have a method __getitem__ in a class which acts
   Gang> like other sequence type.  For example,
   Gang> ------------------------
   Gang> class data:
   Gang> 	  def __init__(self, n):
   Gang> 	      self.maxsize = n
   Gang> 	  def __getitem__(self, k):
   Gang> 	      if k >= self.maxsize:
                            raise IndexError  # !!!

The 'for' loop works that way! It calls __getitem__ until it catched
an IndexError, then it stops.

   Gang> 		    # I want to stop here
   Gang> 		    # ????
   Gang> 	      return get_data_from_some_where_else(k)
   Gang> d = data(10)
   Gang> for el in d:
   Gang> 	  print el
   Gang> ------------------------
   Gang> I want to make it stop at some point automatically, like
   Gang> range() does. I don't want to use try: exception clause for
   Gang> this. Is there any way for this?

No try ... except clause necessary, but a 'raise' is! ;-)

   Gang> Thanks
   Gang> Gang Seong

You're welcome,

More information about the Python-list mailing list