In the NumPy documentation, it is demonstrated that you can add a custom attribute by subclassing the ndarray:
import numpy as np
class RealisticInfoArray(np.ndarray):
def __new__(cls, input_array, info=None):
obj = np.asarray(input_array).view(cls)
obj.info = info
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.info = getattr(obj, 'info', None)
arr = np.arange(5)
obj = RealisticInfoArray(arr, info='information')
print(obj.info)
This example works perfectly fine. However, if I want to make the new attribute “private” (i.e., by calling the attribute self._info
):
import numpy as np
class RealisticInfoArray(np.ndarray):
def __new__(cls, input_array, info=None):
obj = np.asarray(input_array).view(cls)
obj.info = info
return obj
def __array_finalize__(self, obj):
if obj is None: return
self._info = getattr(obj, 'info', None)
arr = np.arange(5)
obj = RealisticInfoArray(arr, info='information')
print(obj._info)
Then None
is printed. Can somebody help me understand why this is and how to fix this so that obj._info
is not None
and behaves the same as the first example?