1

I have such a class

class Point:
    def __init__(self, x,y,z):
        self.x = x
        self.y = y
        self.z = z

where x,y,z are float

and I want to do this:

p = Point(0,0,0)
arr_p = np.array(p)
arr_pts = np.array([p])

what I expect:

>>> arr_p
array([0., 0., 0.])
>>> arr_pts
array([[0., 0., 0.]])

and both have dtype=np.float64

How can I customize my class to achieve this?

What I've tried: I saw some comments in numpy.array

        object : array_like
            An array, any object exposing the array interface, an object whose
            __array__ method returns an array, or any (nested) sequence.

so I simply added

    def __array__(self):
        return [self.x, self.y, self.z]

But it doesn't work....I don't know what does it mean by array, is it C level thing that we need to manage the memory layout?

3
  • have you tried anything yet? Commented Jun 5, 2019 at 22:22
  • 3
    it is not clear to me exactly what you are trying to achieve. Can you give example input/output? Commented Jun 5, 2019 at 22:27
  • What's p? A list of Point instances? Be clear. Commented Jun 5, 2019 at 23:24

1 Answer 1

2

You can define the __len__ and __getitem__ method:

class Point:
    def __init__(self, x,y,z):
        self.x = x
        self.y = y
        self.z = z

    def __len__(self):
        return 3

    def __getitem__(self, idx):
        return (self.x, self.y, self.z)[idx]
Sign up to request clarification or add additional context in comments.

Comments

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.