Multiple constructors

Terry Reedy tjreedy at udel.edu
Sun Feb 6 03:58:08 EST 2005


"Philip Smith" <as006d4848 at blueyonder.co.uk> wrote in message 
news:6SjNd.38337$K7.21639 at fe2.news.blueyonder.co.uk...
> Call this a C++ programmers hang-up if you like.
>
> I don't seem to be able to define multiple versions of __init__ in my 
> matrix

Correct.

> class (ie to initialise either from a list of values or from 2 dimensions 
> (rows/columns)).
>
> Even if Python couldn't resolve the __init__ to use on the basis of 
> argument types surely it could do so on the basis of argument numbers???

Variable parameter counts are handled either with default values or the 
*restlist and **keydict mechanisms.

Keep in mind that the compiler cannot, in general, know, at compile time, 
what function object will be bound to a name at run time.  And that you can 
have only bind a name to one object.

> At any rate - any suggestions how I code this????

The usual way is to write your own dispatch code to either execute the 
appropriate code block or call the appropriate function.

Or you could write a function of functions that returns a function that 
dispatches to one of the functions according to its arg count.  Something 
like (untested, all exceptions passed through):

def arg_count_dispatcher_maker(*funcs):
    def arg_count_dispatcher(*args):
        return funcs[len(args)](*args)
    return arg_count_dispatcher

which you use like this:
    __init__ = arg_count_dispatcher_maker(func0, func1, func2)

Terry J. Reedy 






More information about the Python-list mailing list