python function overloading

Function overloading? Simple appreciated that supports multiple functions with the same name is defined, but a different number or type of parameters, at the time of the call, or the number of the interpreter based on the type of parameters, calling the corresponding function.

Python function parameter is very flexible, we can only define a function to achieve the same functionality, 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

Python To achieve similar functionality, can make use of 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)
Other: zzz
Int: 1
Float: 1.2

Note that this approach can only function is to determine the final call depending on the type of the first argument.

For more details see the official documents of singledispatch

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

Guess you like

Origin www.cnblogs.com/pfeiliu/p/12393283.html