是否可以在Python中使用重载函数?在C#中我会做类似
的事情void myfunction (int first, string second)
{
//some code
}
void myfunction (int first, string second , float third)
{
//some different code
}
然后当我调用函数时,它会根据参数的数量区分两者。是否有可能在Python中做类似的事情?
答案 0 :(得分:95)
编辑对于Python 3.4中的新单调度泛型函数,请参阅http://www.python.org/dev/peps/pep-0443/
您通常不需要在Python中重载函数。 Python是dynamically typed,并且支持函数的可选参数。
def myfunction(first, second, third = None):
if third is None:
#just use first and second
else:
#use all three
myfunction(1, 2) # third will be None, so enter the 'if' clause
myfunction(3, 4, 5) # third isn't None, it's 5, so enter the 'else' clause
答案 1 :(得分:45)
在普通的python中,你无法做你想做的事。有两个接近的近似值:
def myfunction(first, second, *args):
# args is a tuple of extra arguments
def myfunction(first, second, third=None):
# third is optional
然而,如果你真的想要这样做,你当然可以让它发挥作用(冒着冒犯传统主义者的风险; o)。简而言之,您可以编写一个wrapper(*args)
函数,根据需要检查参数和委托的数量。这种“黑客”通常是通过装饰者完成的。在这种情况下,您可以实现以下目标:
from typing import overload
@overload
def myfunction(first):
....
@myfunction.overload
def myfunction(first, second):
....
@myfunction.overload
def myfunction(first, second, third):
....
您可以通过使overload(first_fn)
函数(或构造函数)返回__call__(*args)
方法所做的可调用对象来实现此功能上面说明了授权,overload(another_fn)
方法添加了可以委派给的额外功能。
你可以在这里找到一个类似的例子http://acooke.org/pytyp/pytyp.spec.dispatch.html但是按类型重载方法。这是一种非常相似的方法......
更新:类似的东西(使用参数类型)被添加到python 3 - http://www.python.org/dev/peps/pep-0443/
答案 2 :(得分:6)
是的,这是可能的。我在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选择要调用的函数,具体取决于未命名参数的数量。
解决方案并不完美,但目前我不能写得更好。
答案 3 :(得分:1)
不可能直接。您可以对给出的参数使用显式类型检查,尽管这通常不赞成。
Python是动态的。如果你不确定一个对象可以做什么,只需尝试:并在其上调用一个方法,然后除了:errors。
如果您不需要根据类型重载,只需要根据参数的数量重载,请使用关键字参数。
答案 4 :(得分:0)
重载方法在python中很棘手。但是,可以使用传递dict,list或原始变量。
我已经为我的用例尝试了一些东西,这可以帮助理解人们重载方法。
让我们在stackoverflow线程之一中使用示例:
一个类重载方法,调用来自不同类的方法。
def add_bullet(sprite=None, start=None, headto=None, spead=None, acceleration=None):
传递来自远程类的参数:
add_bullet(sprite = 'test', start=Yes,headto={'lat':10.6666,'long':10.6666},accelaration=10.6}
或add_bullet(sprite = 'test', start=Yes,headto={'lat':10.6666,'long':10.6666},speed=['10','20,'30']}
因此,正在从方法重载中实现列表,字典或原始变量的处理。
试试你的代码