Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function overloading in Python: Missing [closed]

As function overloading says:

Function overloading is absent in Python.

As far as I feel this a big handicap since its also an object-oriented (OO) language. Initially I found that unable to differentiate between the argument types was difficult, but the dynamic nature of Python made it easy (e.g. list, tuples, strings are much similar).

However, counting the number of arguments passed and then doing the job is like an overkill.

like image 978
Xolve Avatar asked Apr 09 '09 07:04

Xolve


People also ask

Why doesn't Python have function overloading?

Why no Function Overloading in Python? Python does not support function overloading. When we define multiple functions with the same name, the later one always overrides the prior and thus, in the namespace, there will always be a single entry against each function name.

Does function overloading exist in Python?

Python does not support function overloading as in other languages, and the functional parameters do not have a data type.

Which conversion function Cannot be overloaded in a class in Python?

Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well.


2 Answers

Now, unless you're trying to write C++ code using Python syntax, what would you need overloading for?

I think it's exactly opposite. Overloading is only necessary to make strongly-typed languages act more like Python. In Python you have keyword argument, and you have *args and **kwargs.

See for example: What is a clean, Pythonic way to have multiple constructors in Python?

like image 179
vartec Avatar answered Oct 12 '22 08:10

vartec


As unwind noted, keyword arguments with default values can go a long way.

I'll also state that in my opinion, it goes against the spirit of Python to worry a lot about what types are passed into methods. In Python, I think it's more accepted to use duck typing -- asking what an object can do, rather than what it is.

Thus, if your method may accept a string or a tuple, you might do something like this:

def print_names(names):     """Takes a space-delimited string or an iterable"""     try:         for name in names.split(): # string case             print name     except AttributeError:         for name in names:             print name 

Then you could do either of these:

print_names("Ryan Billy") print_names(("Ryan", "Billy")) 

Although an API like that sometimes indicates a design problem.

like image 30
Ryan Ginstrom Avatar answered Oct 12 '22 07:10

Ryan Ginstrom