python中重载的函数?

Trc*_*rcx 83 python arguments overloading function

是否有可能在Python中重载函数?在C#中,我会做类似的事情

void myfunction (int first, string second)
{
//some code
}
void myfunction (int first, string second , float third)
{
//some different code
}
Run Code Online (Sandbox Code Playgroud)

然后当我调用函数时,它会根据参数的数量区分两者.是否有可能在Python中做类似的事情?

agf*_*agf 96

编辑有关Python 3.4中新的单调度泛型函数,请参阅http://www.python.org/dev/peps/pep-0443/

您通常不需要在Python中重载函数.Python是动态类型的,并支持函数的可选参数.

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
Run Code Online (Sandbox Code Playgroud)

  • 好吧,重载/多态和条件之间存在差异.你的意思是我们不需要多态,因为我们有条件吗? (8认同)
  • 但是请注意,基于参数的* type *调用不同的函数要困难得多(尽管并非不可能)。 (3认同)
  • @navidoo我认为这不是一个好主意 - 一个函数不会返回完全不同类型的东西.但是,您始终可以在main函数内部定义本地生成器函数,调用它并返回生成的生成器 - 从外部它将与主函数是生成器相同.[此处示例.](https://gist.github.com/agfor/a81e60d5ae4bd8db70ca) (2认同)

and*_*oke 47

在普通的python你不能做你想要的.有两个接近的近似值:

def myfunction(first, second, *args):
    # args is a tuple of extra arguments

def myfunction(first, second, third=None):
    # third is optional
Run Code Online (Sandbox Code Playgroud)

但是,如果你真的想这样做,你当然可以让它发挥作用(冒着冒犯传统主义者的风险; o).简而言之,您可以编写一个wrapper(*args)函数来检查参数和委托的数量.这种"黑客"通常是通过装饰者完成的.在这种情况下,您可以实现以下目标:

from typing import overload

@overload
def myfunction(first):
    ....

@myfunction.overload
def myfunction(first, second):
    ....

@myfunction.overload
def myfunction(first, second, third):
    ....
Run Code Online (Sandbox Code Playgroud)

并且你通过使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/


Gin*_*lus 7

是的,这是可能的.我在Python 3.2.1中编写了以下代码:

def overload(*functions):
    return lambda *args, **kwargs: functions[len(args)](*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

用法:

myfunction=overload(no_arg_func, one_arg_func, two_arg_func)
Run Code Online (Sandbox Code Playgroud)

请注意,overload函数返回的lambda 根据未命名参数的数量选择要调用的函数.

解决方案并不完美,但目前我不能写得更好.