Python中的重载函数 [英] Overloaded functions in Python
本文介绍了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屋!
查看全文