Two-key indexer in python

I am new to python. I want to write a class with two keys as an indexer. should also be able to use them inside the class as follows:

a = Cartesian(-10,-10,10,10) # Cartesian is the name of my class
a[-5][-1]=10

and in the Cartesian class:

def fill(self,value):
   self[x][y] = x*y-value

I'm trying with

def __getitem__(self,x,y):
  return self.data[x-self.dx][y-self.dy]

but does not work.

+5
source share
3 answers

If you just need a lightweight application, you can __getitem__take a tuple:

def __getitem__(self, c):
  x, y = c
  return self.data[x-self.dx][y-self.dy]

def __setitem__(self, c, v):
  x, y = c
  self.data[x-self.dx][y-self.dy] = v

and use like this:

a[-5,-1] = 10

However, if you are doing a lot of numerical calculations or it is an integral part of your application, think about using Numpy and just present this coordinate as a vector: http://numpy.scipy.org/

+8
source

- , Cartesian()? , ? , .

, .coordinate(x, y) .

+1

Take the tuple:

>>> class Foo(object):
...     def __getitem__(self, key):
...         x, y = key
...         print x, y
... f = Foo()
... f[1,2]
1 2
+1
source

All Articles