0

I have some data stored in a object Foo().

Foo.data is a list of n x m np.array, where each array represent some experimental data at a specific time. The array is composed by m variables, and n correspond to the number of different point where measurement has been taken.

We can consider that we have at our disposal a list of variables name, e.g:

var_names=['x','volume','u','L_bar','rho','P',.....]

I want like to make data more accessible, defining something like:

def Foo.P(self,x,time)
    index_t=time_list.index(time)
    index_x=var_names.index(x)
    index_P=var_names.index(P)
    return Foo.data[index_t][index_x,index_P]

The question is: considering that the list of variables is not fixed,but it can vary, can I automatically define some functions that do what I show before without explicitly defining one for each variable?

I mean, I would like to have a bunch of function such as, Foo.P, Foo.volume, Foo.u, Foo.rho that extract the value of the variable given by the function name, for a (x,time) position, without defining all of them one by one.

Pierpaolo
  • 1,721
  • 4
  • 20
  • 34

2 Answers2

2

You can do it by defining the special __getattr__ method on Foo, like this:

def __getattr__(self, name):
    """If name is known, return a function to get that data for given (x, time)."""
    if name not in var_names: # name not known
        raise AttributeError
    return lambda x, time: self.data[time_list.index(time)][var_names.index(x), var_names.index(name)]
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1

Why don't you just pass the name through? Like this:

#!/usr/bin/python
# -*- coding: utf-8 -*-


var_names=['x','volume','u','L_bar','rho','P']

def general_foo(self, name, x, time)
    index_t=time_list.index(time)
    index_x=var_names.index(x)
    index_P=var_names.index(name)
    return Foo.data[index_t][index_x,index_P]

for var in var_names:
    general_foo(var, x, time)
Stephen Lin
  • 4,852
  • 1
  • 13
  • 26
  • Yeah, that was my initial idea, but I was looking some something "looking better" (ie calling directly by the variable name), and then the question seemed (to me) interesting. – Pierpaolo Jan 12 '15 at 08:26
  • @thunder1123 Then you will have to use lambda and getattr. But from my point of view, they are the same. lambda part is the general part. Meanwhile, lambda will make code not so readable. – Stephen Lin Jan 12 '15 at 08:43