Search code examples
pythonnumpygetter-settercorrectness

Setters and getters that act like lists/tuples


I have a project that uses Numpy. One of the classes needs a set of matrices called weights. For several reasons, it's best if I store all these matrix values as one long vector, and let each separate matrix be a view of a slice of that.

self.weightvector = asmatrix(rand(nweights, 1)) # All the weights as a vector
self.weights = list() # A list of views that have the 'correct' shape

for i in range(...):
    self.weights.append(...)

If the user of the class does something like foo.weights[i] = bar, then these weights will no longer be views into the original weight vector.

Does Python offer a mechanism through which can define getters and setters for when an indexing such as foo.weights[i] = bar is done?


Solution

  • Sure. You want to override the __setitem__ method on your class.

    class Weights(list):
    
        def __setitem__(self, key, value):
             ....
    

    Here is a link to the docs:
    http://docs.python.org/2/reference/datamodel.html#object.__setitem__