Ferguzz
Ferguzz

Reputation: 6097

function of a function (property) python

I have a Python class with functions and properties like this:

@property
def xcoords(self):
    ' Returns numpy array. '
    try:
        return self.x_coords
    except:
        self.x_coords = self._read_coords('x')
        return self.x_coords

def _read_coords(self, type):
    # read lots of stuff from big file
    return array

This allows me to do this: data.xcoords, nice and simple.

I want to keep this as it is, however I want to define functions which allow me to do this:

    data.xcoords.mm
    data.xcoords.in

How do I do it? I also want these function to work for other properties of the class such as data.zcoords.mm.

Upvotes: 0

Views: 172

Answers (1)

senderle
senderle

Reputation: 151067

If you really want xcoords to return a numpy array, then people may not expect the value of xcoords to have mm and in_ methods. You should think about whether mm and in_ are really properties of the arrays themselves, or if they are properties of the class you're defining. In the latter case, I would recommend against subclassing ndarray -- just define them as methods of the containing class.

On the other hand, if these are definitely properties of the thing returned by xcoords, then subclassing ndarray is a reasonable approach. Be sure to get it right by defining __new__ and __array_finalize__ as discussed in the docs.

To decide whether you should subclass ndarray, you might consider whether you can see yourself reusing this class elsewhere in your program. (You don't actually have to use it elsewhere, right now -- you just have to be able to see yourself reusing it at some point.) If you can't, then these are probably properties of the containing class. The line of reasoning here is that -- thinking in terms of functions -- if you have a short function foo and a short function bar, and know you will never call them any other way than foo(bar(x)), you might be better off writing foo_bar instead. The same logic applies to classes.

Finally, as larsmans pointed out, in is a keyword in python, and so isn't available for use in this case (which is why I used in_ above).

Upvotes: 3

Related Questions