Python 中的重载函数 [英] Overloaded functions in Python

查看:23
本文介绍了Python 中的重载函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 中是否可以有重载函数?

Is it possible to have overloaded functions in Python?

在 C# 中,我会做类似的事情

In C# I would do something like

void myfunction (int first, string second)
{
    # Some code
}

void myfunction (int first, string second, float third)
{
    # Some different code
}

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

And then when I call the function it would differentiate between the two based on the number of arguments. Is it possible to do something similar in Python?

推荐答案

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

EDIT For the new single dispatch generic functions in Python 3.4, see http://www.python.org/dev/peps/pep-0443/

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

You generally don't need to overload functions in Python. Python is dynamically typed, and supports optional arguments to functions.

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

这篇关于Python 中的重载函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆