In Python 3,
dir(np.array(colour_map.keys()))
shows that this class not satisfy the array_like
requirement which is specified as being necessary in the documentation for numpy.array
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.array.html
The definition of array_like
was explored in more detail here numpy: formal definition of "array_like" objects?
It seems that np.array
doesn't check whether array_like
is satisfied, and will happily construct a Numpy array from an object which does not satisfy it.
Then when you try to index it, the indexing doesn't work.
Here's an example with my_object
designed not to be array_like
.
class my_object():
def greet(self):
print("hi!")
a = my_object()
a.greet()
print(dir(a)) # no __array__ attribute
b = np.array(a)
b[0]
results in
hi!
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'greet']
Traceback (most recent call last):
File "C:/path/to/my/script.py",
line 35, in <module>
b[0]
IndexError: too many indices for array
Now let's try making it array-like (or at least sufficiently array-like for this to work):
class my_object():
def greet(self):
print("hi!")
def __array__(self):
return np.array([self])
a = my_object()
b = np.array(a)
b[0].greet() # Now we can index b successfully
results in:
hi!