I am trying to reference a slice of a "global" numpy array via a object attribute. Here is what I think the class structure would be like and it's use case.
import numpy
class X:
def __init__(self, parent):
self.parent = parent
self.pid = [0, 1, 2]
def __getattr__(self, name):
if name == 'values':
return self.parent.P[self.pid]
else:
raise AttributeError
class Node:
def __init__(self):
self.P = numpy.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
self._values = X(self)
def __getattr__(self, name):
if name == 'x':
return self._values.values
else:
raise AttributeError
Here is the use case:
>>> n = Node()
>>> print n.P
[ 1 2 3 4 5 6 7 8 9 10]
>>> print n.x
[1 2 3]
>>> print n.x[1:3]
[2 3]
Which works fine, now I would like to assign values to n.P
through the n.x
attribute by,
>>> n.x = numpy.array([11, 12, 13])
to get,
>>> print n.P
[ 11 12 13 4 5 6 7 8 9 10]
Or assign values to slices by,
>>> n.x[1:3] = numpy.array([77, 88])
to get,
>>> print n.P
[ 11 77 88 4 5 6 7 8 9 10]
But for the life of me, I'm struggling to get this assignment working. I thought it would be easy using __setattr__
and __setitem__
, but a whole day later I still haven't managed it.
Ultimately, n.x
will be returned as a multi-dimensional array where the X
class will reshape is on return, but is stored in a n.P
which is a vector. I have removed this to simplify the problem.
I would love some help on this. Has anyone done this before? Or suggest how to do this?
Thanks in advance for your help.