Reputation: 15
I'm having some troubles when it comes to multiplying two matrices. An AttributeError appears when I'm trying to perform the addition part
Traceback (most recent call last):
File "MatrixClass.py", line 189, in <module>
main()
File "MatrixClass.py", line 184, in main
mat.multiplyMatrixes(mat1,mat2)
File "MatrixClass.py", line 176, in multiplyMatrixes
self[i][j] += (m1[i][k])*(m2[k][j])
AttributeError: matrix instance has no attribute '__getitem__'
I tried saving the new matrix in another instance called for example m3 but the I thought it would be better to use self instead.
Here's my code:
def multiplyMatrices(self,m1,m2):
if m1.getRows() == m2.getColumns() and m1.getColumns() == m2.getRows():
self.setRows()
self.setColumns()
for i in range(m1.getRows()):
for j in range(m2.getColumns()):
for k in range(m1.getColumns()):
self[i][j] += (m1[i][k])*(m2[k][j])
I created the instance of self in main(), before calling multiplyMatrices()
Upvotes: 0
Views: 227
Reputation: 11681
According to the AttributeError
, you never defined the __getitem__
method in your class. This is how you can control object[key] access. I would suggest reading up on the python data model in general if you are deciding to make a more advanced class (like this one) in python. Although it is a bit strange to have the multiplication of two other matrices being stored in self. I'd probably just create a new matrix in the method and return that.
Upvotes: 1