'Initializing a class with numpy array question

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!



Solution 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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 M Kupperman