Pergunta

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?

Foi útil?

Solução

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__

Outras dicas

More options:

Instead of implementing a new container type, you could reuse the existing one that does what you want, a tuple:

self.weights = tuple()

for i in (...) :
    self.weights += (<new_item>,)

Or if you really want to use a list, make weights a @property and return a copy of the original list.

@property
def weights(self) :
    return [j for j in self._weights]
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top