defining __getitem__

Clemens Hintze c.hintze at gmx.net
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> 
   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> 
   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> 
   Gang> Thanks
   
   Gang> Gang Seong

You're welcome,
Clemens.




More information about the Python-list mailing list