2012-01-15 74 views
0

我想在這裏實現插入功能。那麼,對於這個類是Grid的子類的Matrix,似乎有問題。但我不太明白我在這裏做錯了什麼。 錯誤提示「Grid [m] [n] = value TypeError:'type'對象不可自訂。」python __getitem__重載問題

請幫

感謝

from Grid import Grid 

class Matrix(Grid): 
    def __init__(self, m, n, value=None): 
##  super(Matrix, self).__init__(m, n) 
     Grid.__init__(self, m, n) 

    def insert(self, m, n, value=None): 
     Grid[m][n] = value 

這裏是電網類

from CArray import Array 

class Grid(object): 
    """Represents a two-dimensional array.""" 
    def __init__(self, rows, columns, fillValue = None): 
     self._data = Array(rows) 
     for row in xrange(rows): 
      self._data[row] = Array(columns, fillValue) 
    def getHeight(self): 
     """Returns the number of rows.""" 
     return len(self._data) 
    def getWidth(self): 
     "Returns the number of columns.""" 
     return len(self._data[0]) 
    def __getitem__(self, index): 
     """Supports two-dimensional indexing 
     with [row][column].""" 
     return self._data[index] 
    def __str__(self): 
     """Returns a string representation of the grid.""" 
     result = "" 
     for row in xrange(self.getHeight()): 
      for col in xrange(self.getWidth()): 
       result += str(self._data[row][col]) + " " 
      result += "\n" 
     return result 
+0

爲什麼你將'super'調用註釋掉,並將其替換爲直接的'Grid'調用? '超級'是正確的。請接受一些以前問題的答案。 – 2012-01-15 09:03:37

+0

我認爲超級調用和Grid .__ init__是一樣的。這就是爲什麼。如果我錯了,請糾正我。 – user1047092 2012-01-16 07:46:54

回答

4

您所訪問的Grid,你要尋找的對象。將Grid[m][n] = value更改爲self[m][n] = value

2

無法像數組一樣訪問類,只是對象。 Grid[m][n] = value必須替換爲self[m][n] = value,因爲Grid是類,而不是對象,所以您使用self,因爲所有方法都將當前實例作爲第一個參數傳遞(順便說一句,'self'這個詞真的沒有關係,您如果你想的話可以稱之爲'current_instance'或其他任何東西)。如果您想知道爲什麼Grid表示「類型」對象,請檢查this question的第一個答案。

+0

感謝您的大力幫助! – user1047092 2012-01-16 07:43:27