Method acting on arguements passed

bruno at modulix onurb at xiludom.gro
Fri May 5 14:50:32 CEST 2006

Panos Laganakos wrote:
> I want a class method to take action depending on the type of the
> arguement passed to it.
> ie:
> getBook(id) # get the book by ID
> getBook(name) # get the book by name
> ...
> Other languages use the term function/method overloading to cope with
> this. And when I googled about it seems that GvR is testing it for 3.0
> inclusion or so.
> I was thinking of right after the function declaration check for the
> parameter passed by isinstance() or type() and use if..elif..else to
> act.
> Is this the pythonic way/best practice to apply here?

For simple case and if there's no need for extensibility, this is
usually quite enough - even if somewhat ugly. If the code for each case
is really different, I'd split the whole thing into three separate
methods : getBookById, getBookByName, and getBook that only do the

Else - and depending on the context, needs, specs and whatnot, I'd look
either at the visitor pattern (or any custom double-dispatch) or at an
existing multimethod implementation (like David Mertz's multimethod or
Philip Eby's protocol.dispatch).

My 2 cents
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"

More information about the Python-list mailing list