Description of the original problem
The problem arises when I implement some machine learning algorithm with numpy . I need a new ludmo class that works the same as numpy.ndarray but has a few more properties. For example, with the new ludmo.foo property. I have tried several methods below, but none of them are satisfactory.
1. Packing
First I created a wrapper class for numpy.ndarray since
import numpy as np class ludmo(object): def __init__(self) self.foo = None self.data = np.array([])
But when I use some function (in scikit-learn , which I cannot change) to manipulate the list of the np.ndarray instance, I must first extract all the data fields of each ludmo object and collect them into a list. After that, the list is sorted, and I lost the correspondence between the data and original ludmo .
2. Inheritance
Then I tried to make ludmo subclass of numpy.ndarray , since
import numpy as np class ludmo(np.ndarray): def __init__(self, shape, dtype=float, buffer=None, offset=0, strides=None, order=None) super().__init__(shape, dtype, buffer, offset, strides, order) self.foo = None
But another problem arises: the most common way to create a numpy.ndarray object is numpy.array(some_list) , which returns a numpy.ndarray object, and I have to convert it to a ludmo object. But so far I have not found a good way to do this; simply changing the __class__ attribute will result in an error.
I am new to Python and numpy, so there must be some elegant way that I don't know. Any advice is appreciated.
It is better if someone can give a general solution that applies not only to the numpy.ndarray class, but also to any classes.