Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexer with two keys in python

Tags:

python

I'm newbie with python. I want to write a class with two keys as indexer. also need to be able to use them inside of class like this:

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 try with

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

but doesn't work.

like image 287
sorush-r Avatar asked Aug 11 '10 17:08

sorush-r


3 Answers

If you just need a lightweight application, you can have __getitem__ accept 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 numeric computation or this is integral to your application, consider using Numpy and just represent this coordinate as a vector: http://numpy.scipy.org/

like image 193
carl Avatar answered Nov 06 '22 19:11

carl


Is there any reason you actually need to explicitly define a Cartesian() class? For example, are there calculation methods on it? If not, then just use a lists within lists to use this type of syntax.

If you do need a class, then consider adding a .coordinate(x, y) method to it instead and don't bother trying to do the list syntax.

like image 26
Soviut Avatar answered Nov 06 '22 21:11

Soviut


Accept a tuple:

>>> class Foo(object):
...     def __getitem__(self, key):
...         x, y = key
...         print x, y
... f = Foo()
... f[1,2]
1 2
like image 42
Steven Rumbalski Avatar answered Nov 06 '22 21:11

Steven Rumbalski