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.
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/
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.
Accept a tuple:
>>> class Foo(object):
... def __getitem__(self, key):
... x, y = key
... print x, y
... f = Foo()
... f[1,2]
1 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With