首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Python中重载函数?

如何在Python中重载函数?
EN

Stack Overflow用户
提问于 2018-03-05 05:16:56
回答 2查看 0关注 0票数 0

在Python中有可能重载函数吗?在C#中,我这样做的:

代码语言:txt
复制
void myfunction (int first, string second)
{
//some code
}
void myfunction (int first, string second , float third)
{
//some different code
}

在Python中可以做类似的事情吗?

EN

回答 2

Stack Overflow用户

发布于 2018-03-05 13:17:37

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

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2018-03-05 14:19:43

在正常的Python中,你不能做你想做的事。有两个近似的近似值:

代码语言:javascript
复制
def myfunction(first, second, *args):
    # args is a tuple of extra arguments

def myfunction(first, second, third=None):
    # third is optional

你可以实现类似于这样的功能:

代码语言:javascript
复制
from typing import overload

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

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

@myfunction.overload
def myfunction(first, second, third):
    ....
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100003571

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档