Note that this code is not going to be used for anything, it's more of a thought experiment. I've been seeing a lot of NumPy code lately and noticed that they use a custom indexing process, presumably by defining an object's __getitem__
method. I wrote the following class that allows for a multi-dimensional array to be indexed as ls[1,2]
instead of ls[1][2]
.
Is there a better way to write this method? It seems unnecessary to be keeping track of current
as the item look-up is descended, but I can't think of a way to avoid it.
class Array(list):
def __getitem__(self, indices):
current = super(self.__class__, self)
for index in indices:
current = current.__getitem__(index)
return current
a = Array([[[1,2,3],[4,5,6]],
[[0,1,2],[9,8,7]]])
print a[1,0,2] # 2