Python中是否可能有重载函数?在C#中,我会做类似的事情void myfunction (int first, string second){//some code}void myfunction (int first, string second , float third){//some different code}然后当我调用该函数时,它将根据参数的数量在两者之间进行区分。是否可以在Python中做类似的事情?
3 回答

UYOU
TA贡献1878条经验 获得超4个赞
是的,有可能。我在下面的Python 3.2.1中编写了代码:
def overload(*functions):
return lambda *args, **kwargs: functions[len(args)](*args, **kwargs)
用法:
myfunction=overload(no_arg_func, one_arg_func, two_arg_func)
请注意,overload函数返回的lambda 根据未命名参数的数量选择要调用的函数。
解决方案并不完美,但是目前我无法写出更好的东西。
添加回答
举报
0/150
提交
取消