Actually, Python needs two different functions to simulate multiple dispatch (dispatch on both arguments of +
), and it only works for a few “magic” functions. This is discussed in @jeff.bezanson’s PhD thesis:
Numbers tend to be among the most complex features of a language. Numeric types usually need to be a special case: in a typical language with built-in numeric types, describing their behavior is beyond the expressive power of the language itself. For example, in C arithmetic operators like
+
accept multiple types of arguments (ints and floats), but no user-defined C function can do this (the situation is of course improved in C++). In Python, a special arrangement is made for+
to call either an__add__
or__radd__
method, effectively providing double-dispatch for arithmetic in a language that is idiomatically single-dispatch.
In general, Python functions are only “single-dispatch” — when you call obj.method(args...)
, it only looks at the type of obj
. Python provides a somewhat crude form of double dispatch for overloading a few binary operators like +
and *
, but does this by requiring you to implement two “magic methods” (such as __add__
and __radd__
) in general.