Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I rename an array access/write to a variable in python?
    primarykey
    data
    text
    <p>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:</p> <pre><code>//access: value = data[0] //write: data[0] = value </code></pre> <p>If I was working in C, I would do something like this:</p> <pre><code>#define fieldname data[0] //access: value = fieldname //write: fieldname = value </code></pre> <p>How can I do something just as clean in python?</p> <p>EDIT: All of these fields must stay in the numpy array because they get updated by a linear transformation using numpy matrix operations.</p> <p>EDIT: If I write this method:</p> <pre><code>def fieldname(self): return self.data[0] </code></pre> <p>my accesses look as desired, but I cannot write back to data in the same way.</p> <pre><code>//access: value = self.fieldname </code></pre> <p>(self was omitted in the code before this because I felt the problem generalized to situations outside of objects.)</p> <p>This post about overloading the assignment operator might be close to what I want: <a href="https://stackoverflow.com/questions/6012763/how-to-emulate-assignment-operator-overloading-in-python">How to Emulate Assignment Operator Overloading in Python?</a></p> <p>SOLUTION: Write <code>__getattr__</code> and <code>__setattr__</code> 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.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload