No function overloading in python
In order to consider why python does not provide function overloading, first of all we have to study why it is necessary to provide function overloading.
Function overloading is mainly to solve two problems:
Variable parameter type.
The number of variable parameters.
In addition, a basic design principle is that only when the functions of the two functions are exactly the same except for the different parameter types and number of parameters, then function overloading is used. If the functions of the two functions are actually different, then the functions of the two functions are different. Overloading should be used, but a function with a different name should be used.
So for case 1, the function has the same function, but the parameter type is different, how does python handle it?
The answer is that there is no need to deal with it at all, because python can accept any type of parameter. If the function of the function is the same, then different parameter types are likely to be the same code in python, and there is no need to make two different functions.
So for case 2, the function has the same function, but the number of parameters is different, how does python handle it?
The answer is the default parameters. The problem can be solved by setting the missing parameters as default parameters. Because you assume that the functions are the same, the missing parameters will eventually be needed. Well, given that both cases 1 and 2 have solutions, python naturally does not need function overloading.
Knowledge point supplement:
Suppose you have a function connect, which has a parameter address. This parameter may be a string or a tuple. E.g:
connect('123.45.32.18:8080')connect(('123.45.32.18',8080))
You want to be compatible with these two ways of writing in the code, so you might write the code like this:
def connect(address):ifisinstance(address, str):
ip, port = address.split(':')
elif isinstance(address, tuple):
ip, port = address
else:print('Incorrect address format')
So far, this article on Is there any function overloading in python is introduced here. For more detailed explanations of relevant python function overloading, please search ZaLou.Cn
Recommended Posts