Classes and Functions - General Questions
Andreas Hartl
nd at mad.scientist.com
Wed Oct 18 17:38:54 EDT 2006
Setash schrieb:
> 2) Function overloading - is it possible?
>
> Can I have the following code, or something which acts the same in
> python?:
>
>
> def function(a, b)
> do things
>
> def function(a, b, c)
> do things only if I get a third argument
Several ways. The simplest and often most feasible is to create a
3-argument function with a default value for its last argument
def function(a, b, c=None):
if c is None:
do things you need to do with the third argument
else:
do things
Alternatively, you may use a *params argument that consumes an arbitrary
number of arguments
def function(*params):
if len(params) == 2:
do 3-argument things
elif len(params) == 3:
do 2-argument things
You can of course mix and match *params with preceding parameters.
There is a third option - an experimental dynamic function overloading
module, see BDFL's weblog
<http://www.artima.com/weblogs/viewpost.jsp?thread=155514>:
from overloading import overloaded
@overloaded
def function(a, b):
do things
@function.register(object, object, object)
def function_3(a, b, c):
do things with 3 parameters
However, I would not recommend this last solution unless you have a
really, really weird problem that also heavily depends on the type of
parameters. Simply stick to the first one, this will be sufficient for
>90% of all cases.
Andreas
More information about the Python-list
mailing list