在Python中有可能重载函数吗?在C#中,我这样做的:
void myfunction (int first, string second)
{
//some code
}
void myfunction (int first, string second , float third)
{
//some different code
}
在Python中可以做类似的事情吗?
发布于 2018-03-05 13:17:37
你通常不需要在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
发布于 2018-03-05 14:19:43
在正常的Python中,你不能做你想做的事。有两个近似的近似值:
def myfunction(first, second, *args):
# args is a tuple of extra arguments
def myfunction(first, second, third=None):
# third is optional
你可以实现类似于这样的功能:
from typing import overload
@overload
def myfunction(first):
....
@myfunction.overload
def myfunction(first, second):
....
@myfunction.overload
def myfunction(first, second, third):
....
https://stackoverflow.com/questions/-100003571
复制相似问题