Organisation of python classes and their methods

Paul Rubin no.email at nospam.invalid
Fri Nov 2 19:29:01 CET 2012


Martin Hewitson <martinhewitson at mac.com> writes:
>> you want just ONE method, something like "map"...
> Well, because one of the features that the framework will have is to
> capture history steps (in a tree structure) so that each processing
> step the user does is tracked. So while methods such as abs(), cos(),
> etc will eventually just call a built-in method, there will be some
> house-keeping around them. 

Make the "map" wrapper do the house-keeping.

> turns out that in Python, this is more naturally achieved (I think) if
> each algorithm is implemented as a class, so that each algorithm can
> return its set of supported parameters for validation against the user
> inputs and, ultimately, for inclusion in a step in the history
> tree. Since most of that infrastructure will turn out to be
> boiler-plate code, it would make sense to have an algorithm base
> class, which all other algorithms (abs, cos, etc) will inherit
> from. 

That sounds like over-use of classes and inheritance.  It's probably
easiest to just use a dictionary with functions in it (untested):

    from collections import namedtuple
    Ts_func = namedtuple('Ts_func', ['name', func, 'doc', 'validate'])

    all_funcs = {}
    def add_func(name, func, doc, validate):
       all_funcs[name] = Ts_func(name, func, doc, validate)

    add_func('abs', abs, 'absolute value', lambda x: True)
    add_func('acos', math.acos, 'arc cosine', lambda x: abs(x) <= 1)
    ...

You can then look up any of these entries and pass it to your map method.


More information about the Python-list mailing list