I want to create a class that behaves like numpy arrays but possesses additional methods/attributes and have been reading and not fully understanding numpy's guide on subclassing ndarray. On that webpage there is an example that reads
import numpy as np
class RealisticInfoArray(np.ndarray):
def __new__(cls, input_array, info=None):
# Input array is an already formed ndarray instance
# We first cast to be our class type
obj = np.asarray(input_array).view(cls)
# add the new attribute to the created instance
obj.info = info
# Finally, we must return the newly created object:
return obj
def __array_finalize__(self, obj):
# see InfoArray.__array_finalize__ for comments
if obj is None: return
self.info = getattr(obj, 'info', None)
I am confused as to why the lines
obj = np.asarray(input_array).view(cls)
# add the new attribute to the created instance
obj.info = info
do not raise
AttributeError: 'numpy.ndarray' object has no attribute 'info'
I have read in Add an attribute to a Numpy array in runtime that it is related to numpy arrays being implemented in C. Is that the end of the story? How does Python "know" np.array is implemented in C and not a Python class which you can easily add new attributes to?