I have a class with some fields, and I want it to be represented as numpy array.
class Circle:
def __init__(self, cX, cY, rad, color):
self.cX = cX
self.cY = cY
self.rad = rad
self.color = color
# some methods...
I know that in order to print I should define an __str__()
method. Is there a similar mechanism for numpy arrays?
In particular, I want something like this:
list_of_objs = [Circle() for i in range(100)]
numpy_representatin = numpy.asarray(list_of_objs) # shape have to be (4, 100)
Thanks in advance!
UPD: forgot to mention, that all fields are assumed to be of the same type - int
1 Answer 1
I think the following should help you: Writing custom array containers
As mentioned in the above link:
"We can convert to a numpy array using
numpy.array
ornumpy.asarray
, which will call its__array__
-method to obtain a standardnumpy.ndarray
."
Thus, your class could look something like
class Circle:
def __init__(self, cX, cY, rad, color):
self.cX = cX
self.cY = cY
self.rad = rad
self.color = color
def __array__(self):
return np.array([self.cX, self.cY, self.rad, self.color], np.int32)
# some methods...