How to overload Python functions? Case explanation

What is function overloading? It is easy to understand that it supports the definition of multiple functions with the same name, but the number or type of parameters are different. When calling, the interpreter will call the corresponding functions according to the number or type of parameters.

Overloading is implemented in many languages, such as C + +, Java, etc., but Python does not support it. In this article, with some tips, you can make Python support similar functions.
Also note: whether you are for Python employment or hobbies, remember: project development experience is always the core. If you don't have the latest Python introduction to advanced practical video tutorial in 2020, you can go to the small Python exchange : you can find a lot of new Python tutorial projects under the transformation of "seven clothes, nine seven buses and five numbers" (homophony of numbers). You can also communicate with the old driver for advice!

Different number of parameters

Let's see how C + + implements overloading in this case

#include <iostream>
using namespace std;

int func(int a)
{
	cout << 'One parameter' << endl;
}

int func(int a, int b)
{
	cout << 'Two parameters' << endl;
}

int func(int a, int b, int c)
{
	cout << 'Three parameters' << endl;
}
Copy code

If Python defines functions in a similar way, it will not report an error, but the later function definitions will overwrite the previous ones, which cannot achieve the effect of overloading.

>>> def func(a):
...     print('One parameter')
... 
>>> def func(a, b):
...     print('Two parameters')
... 
>>> def func(a, b, c):
...     print('Three parameters')
... 
>>> func(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func() missing 2 required positional arguments: 'b' and 'c'
>>> func(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func() missing 1 required positional argument: 'c'
>>> func(1, 2, 3)
Three parameters
Copy code

But we know that the parameters of Python functions are very flexible. We can define only one function to achieve the same function, like this

>>> def func(*args):
...     if len(args) == 1:
...         print('One parameter')
...     elif len(args) == 2:
...         print('Two parameters')
...     elif len(args) == 3:
...         print('Three parameters')
...     else:
...         print('Error')
... 
>>> func(1)
One parameter
>>> func(1, 2)
Two parameters
>>> func(1, 2, 3)
Three parameters
>>> func(1, 2, 3, 4)
Error
Copy code

Different parameter types

Again, let's see how C + + overloading is implemented in the current situation

#include <iostream>
using namespace std;

int func(int a)
{
	cout << 'Int: ' << a << endl;
}

int func(float a)
{
	cout << 'Float: ' << a << endl;
}
Copy code

In the code, func supports two types of parameters: integer and floating-point. When called, the interpreter looks for the appropriate function based on the parameter type. To implement similar functions in Python, you need to use the functools.singledispatch decorator.

from functools import singledispatch

@singledispatch
def func(a):
	print(f'Other: {a}')

@func.register(int)
def _(a):
	print(f'Int: {a}')

@func.register(float)
def _(a):
	print(f'Float: {a}')

if __name__ == '__main__':
	func('zzz')
	func(1)
	func(1.2)
Copy code

After func function is decorated by functools.singledispatch, two other functions are bound according to different parameter types. When the parameter type is integer or floating-point, a function corresponding to the binding is called; otherwise, the function itself is called.

results of enforcement

Other: zzz
Int: 1
Float: 1.2
 Copy code

It should be noted that this way can only determine the last call function according to the type of the first parameter.

For more details on single dispatch, please refer to the official document

https://docs.python.org/3.6/library/functools.html#functools.singledispatch
Copy code

Note: different return values of functions are also overloaded. There is no better Python implementation, so it is not mentioned

In my opinion, overloading is designed for the flexibility of the language, and python functions have many ingenious designs. It's not necessary to imitate this technology at this time, and it seems that it's against Python's philosophy. Therefore, this article is more about how to imitate, but there is not much explanation for the use scenarios of overloading.
Finally note: whether you are for Python employment or hobbies, remember: project development experience is always the core. If you don't have the latest Python introduction to the advanced practical video tutorial in 2020, you can go to the small Python exchange : you can find a lot of new Python tutorial projects under the transformation of "seven clothes, nine seven buses and five numbers" (homophony of numbers). You can also communicate with the old driver for advice!

The text and pictures of this article come from the Internet and my own ideas. They are only for learning and communication. They have no commercial use. The copyright belongs to the original author. If you have any questions, please contact us in time for handling.

Tags: Python Java

Posted on Mon, 04 May 2020 11:25:11 -0400 by highjo