About "overloading" in python

First, about the difference between python and java:

1. Java defines a function by method name and method list, while python defines a function by method name (functions with the same method name are not allowed to exist)

2. Java implements overloading by defining multiple identical method names and different parameter lists. And python solves the problem of method overloading in the form of default parameters.

So, from this aspect, the implementation of "overloading" in python and java is different.

 

Here's a quote from the Internet about the answer to the question "Why does python not support function overloading like java":

------------The following quotes the original text ------------

In order to consider why python does not provide function overloading, first we have to examine why it is necessary to provide function overloading.

Function overloading is mainly to solve two problems.
1. Variable parameter type.
2. Variable number of parameters.

In addition, a basic design principle is that function overloading is only used when the functions of the two functions are identical except for the parameter types and the number of parameters. If the functions of the two functions are actually different, then the Overloading should be used instead of a function with a different name.

Ok, so for case 1, the function does the same thing, but the parameter types are different, how does python handle it? The answer is that there is no need to deal with it at all, because python can accept parameters of any type. 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 is the same, but the number of parameters is different, how does python handle it? As we all know, the answer is default parameters. Setting those missing parameters to default parameters will solve the problem. Since you're assuming that the functions do the same thing, those missing parameters are needed after all.

Well, since both cases 1 and 2 have solutions, python naturally does not need function overloading.


作者:pansz
链接:https://www.zhihu.com/question/20053359/answer/14054112
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325217434&siteId=291194637