Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python custom class indexing

Is it possible to make a class in python that can be indexed with square brackets but not derived from a different indexed type?

I'm interested in making a class with optional indexes, that would behave like this:

class indexed_array():
    def __init__(self, values):
        self.values = values

    def __sqb__(self, indices):   #This is a made up thing that would convert square brackets to a function
        if len(indices) == 2:
            return self.values[indices[0]][indices[1]]
        elif len(indices) == 1:
            return self.values[indices[0]][0]

myarray = indexed_array([[1,2,3], [4,5,6], [7,8,9]])
print myarray[1, 1]     # returns 5
print myarray[1]        # returns 4

Is there a real method like my __sqb__? Alternatively, can you index a custom class another way?

like image 402
ericksonla Avatar asked Jan 16 '17 22:01

ericksonla


1 Answers

You are need to implement __getitem__. Be aware that a single index will be passed as itself, while multiple indices will be passed as a tuple.

Typically you might choose to deal with this in the following way:

class indexed_array:
    def __getitem__(self, indices):
        # convert a simple index x[y] to a tuple for consistency
        if not isinstance(indices, tuple):
            indices = tuple(indices)

        # now handle the different dimensional cases
        ...
like image 124
donkopotamus Avatar answered Oct 24 '22 04:10

donkopotamus