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?