0

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'] 
4
  • 1
    obj[x:y:z] is equivalent to obj.__getitem__(slice(x,y,z)), and note, the commas are just tuples, so something like obj[x0:y0:z0, x1,y1,z1] is equivalent to obj.__getitem__((slice(x0,y0,z0),slice(x1,y1,z1))) Commented Jan 6, 2020 at 21:32
  • 1
    The : triggers the creation of a slice object; obj[x0:y0:z0, x1,y1,z1] is equivalent to obj.__getitem__((slice(x0,y0,z0), x1, y1, z1). Commented Jan 6, 2020 at 21:47
  • 1
    Technically, I think the commas are part of the syntax, not a tuple expression, though the end result is the same (__getitem__ receiving a tuple). I'm not sure there is any way to observe the difference at the Python level, though. Commented Jan 6, 2020 at 21:48
  • The numpy index_tricks file has a bunch of classes with custom indexing code. It may give you ideas. Commented Jan 6, 2020 at 21:55

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.