1

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 

2 Answers 2

7

You didn't call inherited class constructor and, hence, _data is not defined in your class. Try adding the following in Matrix init:

super(Matrix, self).__init__(m, n, fillValue=value) 
Sign up to request clarification or add additional context in comments.

Comments

3

You have to call the parent's __init__ from your child __init__. Add this to Matrix.__init__:

super(Matrix, self).__init__(m, n, fillValue=value) 

4 Comments

I should add your code into Matrix init? Is this what you mean?
@user1047092, yes. What it does is call Grid.__init__.
Well. After I added the code and tried a = Matrix(2, 3). It says Type Error: __init__() takes at most 4 arguments . I have no idea what's wrong with it.
@user1047092, I made an error in my answer. self should not be passed to __init__. I've fixed my answer above.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.