Trcx Trcx - 1 year ago 101
Python Question

Overloaded functions in python?

Is it possible to have overloaded functions in Python? In C# I would do something like

void myfunction (int first, string second)
//some code
void myfunction (int first, string second , float third)
//some different code
// This maybe a little off, I haven't coded C# in a couple years

and then when I call the function it would differentiate between the two based on the number of arguments. Is it possible to do something similar in Python?

agf agf
Answer Source

EDIT For the new single dispatch generic functions in Python 3.4, see

You generally don't need to overload functions in Python. Python is dynamically typed, and supports optional arguments to functions.

def myfunction(first, second, third = None):
    if third is None:
        #just use first and second
        #use all three

myfunction(1, 2) # third will be None, so enter the 'if' clause
myfunction(3, 4, 5) # third isn't None, it's 5, so enter the 'else' clause
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download