代码之家  ›  专栏  ›  技术社区  ›  sorush-r

python中带两个键的索引器

  •  6
  • sorush-r  · 技术社区  · 14 年前

    我是python的新手。我想写一个有两个键的类作为索引器。还需要能够像这样在类内使用它们:

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

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

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

    3 回复  |  直到 14 年前
        1
  •  12
  •   carl    14 年前

    如果您只需要一个轻量级应用程序,您可以 __getitem__ 接受元组:

    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
    

    使用如下:

    a[-5,-1] = 10
    

    但是,如果要进行大量数值计算或这是应用程序的一部分,请考虑使用Numpy并将此坐标表示为向量: http://numpy.scipy.org/

        2
  •  1
  •   Soviut    14 年前

    Cartesian() 上课?例如,有计算方法吗?如果不是,那么就使用lists中的list来使用这种语法。

    需要一个类,然后考虑添加一个 .coordinate(x, y)

        3
  •  1
  •   Steven Rumbalski    14 年前

    接受元组:

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