Writing a Custom Matrix Class in Python, __setitem__ issues

Question:

I’m working on a custom class to handle matrices using Python. I’m running into a problem where my test program is, apparently, not passing enough arguments to my __setitem__ method. Here’s the code:

def __setitem__(self, rowIndex, colIndex, newVal):
    self.values[rowIndex][colIndex] = newVal

and the test code that’s throwing the error:

M[0, 0] = 5.0;   M[0, 1] = 7.0;   M[0, 2] = -2.0;
M[1, 0] = 3.0;   M[1, 1] = 6.0;   M[1, 2] = 1.0;

M calls the Matrix’s __init__ before attempting to set an item.

And I’m getting this error:

TypeError: __setitem__() takes exactly 4 arguments (3 given)
Asked By: skylerWithAnE

||

Answers:

The error message says it all:

TypeError: __setitem__() takes exactly 4 arguments (3 given)

Your __setitem__ takes 4 (self being passed automatically, like always):

def __setitem__(self, rowIndex, colIndex, newVal):

but this line:

M[0, 0] = 5.0

doesn’t pass 0, 0, and 5.0 to __setitem__; it passes the 2-tuple (0, 0) and the float 5.0 to __setitem__. This is discussed in this section of the Python documentation, where the call pattern is object.__setitem__(self, key, value).

You need something more like

def __setitem__(self, index, value):
    self.values[index[0]][index[1]] = value
Answered By: DSM
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.