1

I have a class:

 class MATRIX:

     # convenience function
     def getDimensions(self,M):
         r = len(M)
         c = len(M[0])
         return r,c

     def add(self,M1,M2):
         res = []
         r1,c1 = self.getDimensions(M1)
         r2,c2 = self.getDimensions(M2)
         if (r1 != r2) or (c1 != c2):
             print("dimensions not the same")
             return res

         for i in range(len(M1)):
             row=[]
             for j in range(len(M1[i])):
                 element=M1[i][j] + M2[i][j]
                 row.append(element)
             res.append(row)

    return res

Simple class, saves no state, just has a function which adds two matrices. I am a beginner at OOP in Python, so, unless I am wrong, all class functions must begin with a self parameter.

The function is meant to be called like:

 Z = MATRIX.add(X,Y)

Where X and Y are matrices

When I try to do this, I get the following error:

 Traceback (most recent call last):
   File "temp.py", line 82, in <module>
Z = MATRIX(X,Y)
 TypeError: object() takes no parameters

In this instance:

 X = [[1,1,1], [2,2,2], [3,3,3]]
 Y = [[4,4,4], [5,5,5], [6,6,6]]

Why is this error showing up? How can I fix it?

4
  • 2
    If this saves no state there is no point making it a class in Python. Commented Mar 1, 2018 at 21:00
  • Add a constructor that takes parameters, if you want to call a constructor MATRIX(X,Y) with parameters.. or fix the incorrect call. Commented Mar 1, 2018 at 21:01
  • 2
    You say you are doing Z = MATRIX.add(X, Y) but the error says Z = MATRIX(X, Y). Which is it? Commented Mar 1, 2018 at 21:02
  • 2
    Note that the line in the error message does not occur in the code you have posted. Commented Mar 1, 2018 at 21:02

1 Answer 1

4

You need to instantiate the class MATRIX like so, before you can use its instance methods:

m = MATRIX()
z = m.add(X, Y)

But if there is no instance data, then there is not much point in having instance methods. In this case you can make the methods static, and not have to instantiate the class to make use of its methods:

class MATRIX:

    # Note that `self` parameter is removed, as it's no longer an
    # instance method.
    @staticmethod
    def add(M1,M2):
         return M1 + M2

z = MATRIX.add(X, Y)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @JL-HN for the edit suggestions, unfortunately I was too late to see it, but I incorporated the changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.