1

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

asked Apr 6, 2020 at 9:51
0

1 Answer 1

3

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 or numpy.asarray, which will call its __array__-method to obtain a standard numpy.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...
answered Apr 6, 2020 at 9:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.