I would like to perform checks on the contents of a numpy array every time it is set. Can python properties be used for this? My approach:
import numpy as np
class Obj():
def __init__(self):
self._np_arr = None
@property
def np_arr(self):
if self._np_arr is None:
self._np_arr = np.ones(10)
return self._np_arr
@np_arr.setter
def np_arr(self, value):
if np.sum(value)>10:
raise ValueError('Error message')
self._np_arr = value
if __name__ == '__main__':
o = Obj()
print o.np_arr
o.np_arr = np.zeros(10) # ok
o.np_arr = np.ones(10)*2 # not ok
print o.np_arr
The getter is entered when the object is still None. Once np_arr is a numpy array the getters and setters no longer work.
What am I doing wrong?