Python: Implementing slicing in __getitem__

Posted by nicotine on Stack Overflow See other posts from Stack Overflow or by nicotine
Published on 2010-05-29T22:52:27Z Indexed on 2010/05/29 23:02 UTC
Read the original article Hit count: 544

Filed under:
|
|

I am trying to implement slice functionality for a class I am making that creates a vector representation.

I have this code so far, which I believe will properly implement the slice but whenever I do a call like v[4] where v is a vector python returns an error about not having enough parameters. So I am trying to figure out how to define the getitem class to handle both plain indexes and slicing.

def __getitem__(self, start, stop, step):
    indx = start
    if stop == None:
        end = start + 1
    else:
        end = stop
    if step == None:
        stride = 1
    else:
        stride = step
    return self.__data[indx:end:stride]

© Stack Overflow or respective owner

Related posts about python

Related posts about slicing