tags:

views:

65

answers:

3

Hi, 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.

+2  A: 

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/

carl
Thanks Carl, python is amazing! I don't know what's numpy , i'll try it. (different with python?)
Sorush Rabiee
Numpy is a python library for numeric computing.
gnud
Numpy is a library for Python that makes numeric computation a bit easier (and faster than native Python). It is similar to Matlab, but for Python. You can do matrix and vector operations quite easily.
carl
A: 

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.

Soviut
I'm just trying python, I don't have to accomplish anything! but it sounds like indexers are more beautiful.
Sorush Rabiee
+1  A: 

Accept a tuple:

>>> class Foo(object):
...     def __getitem__(self, key):
...         x, y = key
...         print x, y
... f = Foo()
... f[1,2]
1 2
Steven Rumbalski
Thanks, (same answer with below :) ...)
Sorush Rabiee