0

I am trying to implement insert function here. Well, for this class Matrix which is the child class of Grid, seem to have problem. But I don't quite understand what I am doing wrong here. The error says " Grid[m][n] = value TypeError: 'type' object is not subscriptable."

Please help

thanks

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

here is Grid class

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
user1047092
  • 1,481
  • 4
  • 17
  • 18
  • Why did you comment out the `super` call and replace it with the direct `Grid` invocation? The `super` was correct. And please, accept some answers to previous questions. – Daniel Roseman Jan 15 '12 at 09:03
  • I think the super call and the Grid.__init__ is the same. that is why. Please correct me if I am wrong. – user1047092 Jan 16 '12 at 07:46

2 Answers2

4

You're accessing the class Grid where you're looking for the object. Change Grid[m][n] = value to self[m][n] = value.

Rob Wouters
  • 15,797
  • 3
  • 42
  • 36
2

Classes can't be accessed like arrays, just objects. Grid[m][n] = value must be replaced with self[m][n] = value, because Grid is the class, not the object, so you use self as all methods are passed the current instance as the first parameter (by the way, the word 'self' really doesn't matter, you could call it 'current_instance' or anything else if you wanted to). If you wonder why it says Grid is a 'type' object, check out the first answer for this question.

Community
  • 1
  • 1
elijaheac
  • 912
  • 2
  • 8
  • 23