什么是函数重载?简单的理解,支持多个同名函数的定义,只是参数的个数或者类型不同,在调用的时候,解释器会根据参数的个数或者类型,调用相应的函数。
重载这个特性在很多语言中都有实现,比如 C++、Java 等,而 Python 并不支持。这篇文章呢,通过一些小技巧,可以让 Python 支持类似的功能。
参数个数不同的情形
先看看这种情况下 C++ 是怎么实现重载的
#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;
}
如果 Python 按类似的方式定义函数的话,不会报错,只是后面的函数定义会覆盖前面的,达不到重载的效果。
>>> 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

本文介绍了函数重载的概念,通常在C++、Java等语言中存在,但Python不直接支持。通过示例展示了如何利用Python的灵活性和functools.singledispatch装饰器模拟函数重载,使Python能根据参数类型调用相应函数。
最低0.47元/天 解锁文章
7194

被折叠的 条评论
为什么被折叠?



