1

Some classes, such as Series in pandas produce instances that can be called by numpy.array and turned into numpy arrays.

How do I make instances of a class that I'm writing (which works with a few arrays at the core) be allowed to be passed as argument to numpy.array and converted to a numpy array?

(perhaps "callable" is not the right word)

Ziofil
  • 1,815
  • 1
  • 20
  • 30

1 Answers1

2

It looks like one easy way is to make the object define an __array__(self) method that returns the array you want numpy.array to return.

You can also make your object a sequence: define __iter__(self) to return an iterator over all the items, __getitem__(self, i), to return the ith element, and and __len__(self) to return the length.

interfect
  • 2,665
  • 1
  • 20
  • 35
  • Of course! I just checked [the docs of numpy.array](https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html) and they say that the first argument is "array_like: An array, any object exposing the array interface, an object whose `__array__` method returns an array, or any (nested) sequence. " – Ziofil Jul 09 '18 at 22:24