table class - inheritance, delegation?
duncan smith
duncan at invalid.invalid
Fri Mar 31 12:50:23 EDT 2017
Hello,
I need to code up a table class, which will be based on numpy
arrays. Essentially it needs to behave like a numpy array, but with a
variable associated with each array dimension. It must (at least
partially) satisfy the API of an existing class. The main reason for the
new class is to avoid the creation of new axes and the transpositions
that were required for elementwise operations on instances of the
original class. So when summing across axes I will retain all the
dimensions. My inclination is to go for composition. e.g. (all following
code untested)
class Table(object):
def __init__(self, values, variables):
self.values = values # numpy array
self.all_variables = variables
self.var_ind_map = dict(zip(variables, range(len(variables))))
@property
def variables(self):
return [v for dim, v in
zip(self.values.shape, self.all_variables)
if not dim == 1]
variables is required by the API. Most binary operators will behave
exactly as for numpy arrays. e.g.
def __mul__(self, other):
return self.__class__(self.values * other.values,
self.all_variables)
I can write a factory method to generate many of these, and maybe
another factory method for __neg__, __pos__, __abs__ etc. But I then
have to deal with __rsub__, __rdiv__ etc. and all I'm doing is emulating
the behaviour of numpy arrays. I also need to handle multipication /
division etc. by e.g. floats in exactly the same way as numpy.
What I can't immediately see is a clean way of doing this with
delegation. But I'm unsure that inheritance is the best way to go (the
class will be very lightweight compared to numpy arrays). Any advice
welcome. I'm currently using Python 2.7 (but will make the move to 3 at
some point). Cheers.
Duncan
More information about the Python-list
mailing list