No function overloading in python
In order to consider why python does not provide function overloading, we first need to examine why it is necessary to provide function overloading.
Function overloading is primarily intended to solve two problems:
Variable parameter type.
Number of variable parameters.
In addition, a basic design principle is that function overloading is used only when the functions are identical except for the type and number of arguments, and if the functions are in fact different, then overloading should not be used, and a function with a different name should be used.
So for case 1, where the function has the same function but different argument types, how does python handle this?
The answer is that you don't need to deal with it at all, because python can take any type of argument, and if the function has the same function, then the different argument types are likely to be the same code in python, and there's no need to make two different functions.
So for case 2, where the function has the same function but a different number of arguments, what does python do?
The answer is the default parameters. Setting the missing parameters as default parameters solves the problem. Since you're assuming that the function does the same thing, you'll need those missing parameters anyway. Well, now that both case 1 and case 2 have been solved, python naturally doesn't need function overloading.
Knowledge Points Supplement:
Suppose you have a function connect that takes one argument, address, which may be a string or a tuple. Example:
connect('123.45.32.18:8080') connect(('123.45.32.18', 8080))
You want to be compatible with both ways of writing inside your code, so you might write your code like this:
def connect(address): if isinstance(address, str): ip, port = (':') elif isinstance(address, tuple): ip, port = address else: print('Incorrect address format')
to this article on python function overloading article is introduced to this, more related python function overloading content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!