I am trying to implement addition function of Matrix. (that is, adding two matrixes) I am doing this by overloading addition function so that two matrix can be added. For this Matrix class, I inherited Grid class to implement.
I seem to have a problem in __add__ method here but can quite figure it out. The error says AttributeError: 'Matrix' Object has no attibute '_data'.
Here is my code. Please can anyone help? or explain?
thanks
from Grid import Grid class Matrix(Grid): def __init__(self, m, n, value=None): self.matrix = Grid(m, n) self.row = m self.col = n def insert(self, row, col, value): self.matrix[row][col] = value print self.matrix def __add__(self, other): if self.row != other.row and self.column != other.column: print " Matrixs are not indentical." else: for row in xrange(self.row): for col in xrange(self.col): self.matrix[row][col] = self.matrix[row][col] + other[row][col] return self.matrix Here is the Grid class which I inherited.
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