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?
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
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With