本文介绍了在Python重载功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
时有可能有重载函数在Python?在C#中我会做这样的事情。
Is it possible to have overloaded functions in Python? 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
}
// This maybe a little off, I haven't coded C# in a couple years
,然后当我调用该函数将在两者之间基于参数的数量区分。是否有可能做在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?
推荐答案
修改:用于在Python 3.4新单牒的通用功能,看到的
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重载功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!