I have an object which contains many of it's fields in a numpy array (they are all of type float64). Some of these fields have meaningful names that I would like to use when accessing/writing, but with my current knowledge, I have to access and write like this:
//access:
value = data[0]
//write:
data[0] = value
If I was working in C, I would do something like this:
#define fieldname data[0]
//access:
value = fieldname
//write:
fieldname = value
How can I do something just as clean in python?
EDIT: All of these fields must stay in the numpy array because they get updated by a linear transformation using numpy matrix operations.
EDIT: If I write this method:
def fieldname(self):
return self.data[0]
my accesses look as desired, but I cannot write back to data in the same way.
//access:
value = self.fieldname
(self was omitted in the code before this because I felt the problem generalized to situations outside of objects.)
This post about overloading the assignment operator might be close to what I want: How to Emulate Assignment Operator Overloading in Python?
SOLUTION:
Write __getattr__
and __setattr__
methods that take field names and do the necessary operations on self.data. These will not get called when the field name provided matches the field name of another attribute other than data, and add the functionality of getting stuff from data when names of these special attributes are provided.