0

So I have defined the following function to be entered into a class:

MatrixConverter(arr)

Which works exactly how I want it to, taking in a numpy array as argument, and produces a simpler matrix as a numpy array.

Now, I would like to define a class that is initialized by a numpy array, and once I enter a matrix into the class, called SeveralConvertor, to run the entered matrix through MatrixConverter, thus creating an internal representation of the converted matrix. My attempt at this goes as follows:

class SeveralConvertor:
    def __init_(self,matrix)
    self.matrix=np.array(matrix)

def MatrixConverter(self)

Letting q be some random array, and then typing q.MatrixConverter gives the following error:

<bound method SeveralConverter.MatrixConverter of <__main__.SeveralConverter object at 0x7f8dab038c10>>

Now, as I said, the function MatrixConverter(arr) works fine as a function, but when I entered it into the class, I exchange all arr for self, which might have something to do with the problem.

Help would be much appriciated!

1
  • 1
    q.MatrixConverter doesn't call this method, so the expression evaluates to the bound method SeveralConverter.MatrixConverter itself. It has nothing to do with NumPy. Commented May 12, 2022 at 21:07

1 Answer 1

1

No need to do anything too fancy, we can bind the (unit tested) function to a class method, then invoke that in the __init__ function.


def matrixConverter(arr):
    # Some complicated function you already wrote
    raise NotImplementedError

class SeveralConverter:
    def __init__(self, matrix):
        self.matrix = self._MatrixConverter(matrix)
    
    @staticmethod
    def _MatrixConverter(arr):
        """ Call the Matrix Converter Function """
        return MatrixConverter(arr)

Then in your code (put the above in a module and import the class)

matrix_converted = SeveralConverter(ugly_matrix)
print(matrix_converted.matrix)  # Prints the converted matrix
Sign up to request clarification or add additional context in comments.

3 Comments

@M Kupperman Thank you very much for your comment! However, two errors occur: When I let x be some np.array and then type SeveralConverter(x), it yields "name 'SeveralConverter' is not defined". Sorry for the inconvenience, I am quite new to python.
The general workflow for a script (no modules/importing user code) looks like: 1. Implement function. 2. Implement class. 3. Call class. We need to see code to debug.
@M Kupperman this ended up working, forgot a small "_". Thank you very much!

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.