Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 } 

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?

like image 835
Trcx Avatar asked Aug 18 '11 19:08

Trcx


People also ask

Can you have overloaded functions in Python?

No. You cannot strictly speaking, overload Python functions. One reason being is that types are not specified in function definitions (the language is Dynamically Typed anyway, and accepts optional function arguments.)

What is overloading in Python with example?

Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class.

Which functions are overloaded?

An overloaded function is really just a set of different functions that happen to have the same name. The determination of which function to use for a particular call is resolved at compile time. In Java, function overloading is also known as compile-time polymorphism and static polymorphism.


1 Answers

EDIT For the new single dispatch generic functions in Python 3.4, see http://www.python.org/dev/peps/pep-0443/

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     else:         #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 
like image 149
agf Avatar answered Sep 19 '22 03:09

agf