Ziofil
Ziofil

Reputation: 2107

How to make python object callable by numpy.array()

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)

Upvotes: 1

Views: 602

Answers (1)

interfect
interfect

Reputation: 2877

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.

Upvotes: 2

Related Questions