Suppose I have a class:
class Data: data: np.ndarray def __init__(self): self.data = np.zeros((10,10)) self.str2col = { str(i):i for i in range(0,10) } def __get_col(self,i): """ @param i: STR or INT """ if isinstance(i,int): return i if isinstance(i,str): return self.str2col[i] raise Exception("Invalid index") Assuming I haven't made any errors, I can index this class as follows:
i = '4' j = 4 obj = Data() point = obj.data[obj.__get_col(i),obj.__get_col(j)] The question is: how does one, in python, overload the "[]" such that I can write, in full numpy indexing syntax,
data = obj[:,:] data = obj['1',:] data = obj[:,'2']
obj[x:y:z]is equivalent toobj.__getitem__(slice(x,y,z)), and note, the commas are just tuples, so something likeobj[x0:y0:z0, x1,y1,z1]is equivalent toobj.__getitem__((slice(x0,y0,z0),slice(x1,y1,z1))):triggers the creation of asliceobject;obj[x0:y0:z0, x1,y1,z1]is equivalent toobj.__getitem__((slice(x0,y0,z0), x1, y1, z1).__getitem__receiving a tuple). I'm not sure there is any way to observe the difference at the Python level, though.index_tricksfile has a bunch of classes with custom indexing code. It may give you ideas.