Trouble when overloading operator[ ]

david_ullrich at my-deja.com david_ullrich at my-deja.com
Thu Jul 20 11:40:42 EDT 2000


In article <8l720o$lr4$1 at nnrp1.deja.com>,
  manolop at my-deja.com wrote:
> Hi!
>
> I need to overload the [ ] operator in a class, so that I can do
things
> like my_class[2][3]

   As someone else said, that will not work unless
__getitem__ returns an object with a __getitem__
method (or an actual sequence).

   You can use the notation [2,3] to accomplish the same
thing: it appears that if you use multiple indices they
get passed as a tuple to __getitem__:

class C:
  def __getitem__(self, index):
    """Returns the sum of the indices passed:"""
    if type(index) == TupleType:
      return reduce(lambda x , y: x + y, index)
    else:
      return index

c = C()
print c[2,3]
print c[5]
print c[1,1,1,1,1]

> Everything works fine when I only use one [ ] and the correct values
> are passed to __getitem__, but I run into trouble when I add the
second
> [ ].  Should I use __getitem__ for the double[ ] or is there another
> method? O:-)
>
> TIA
>
> Sent via Deja.com http://www.deja.com/
> Before you buy.
>


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list