python中的函数签名

Function signature in python

本文关键字:函数 python      更新时间:2023-10-16

在C++中,只要签名不同,就可以创建两个同名函数。因此,例如myfunc(int x)myfunc(float x)不同。在python中,你不能这样做,那么,你需要用不同的名称定义函数吗?或者有更好的方法来处理这种情况吗?

在Python3.4+中,您可以使用functools.singledispatch装饰器,它允许您定义一个通用函数,然后针对它注册类型化实现。

从文档

通用功能:

>>> from functools import singledispatch
>>> @singledispatch
... def fun(arg, verbose=False):
...     if verbose:
...         print("Let me just say,", end=" ")
...     print(arg)

键入的功能:

>>> @fun.register(int)
... def _(arg, verbose=False):
...     if verbose:
...         print("Strength in numbers, eh?", end=" ")
...     print(arg)
...
>>> @fun.register(list)
... def _(arg, verbose=False):
...     if verbose:
...         print("Enumerate this:")
...     for i, elem in enumerate(arg):
...         print(i, elem)

早期版本的Python没有内置的解决方案,但GuidovanRossum在博客中介绍了一个使用decorator的python2解决方案。(编辑:pypi上还有一个用于pythons 2.6-3.3的3.4功能的后台端口)

编辑:当然,使用Python的优点之一是,相同的代码通常可以处理int和float,而无需对类型进行显式调度,这也是最近才添加该功能的原因之一。

Python并不真正关心参数是整数还是浮点。它是动态类型的。例如,你可以这样做:

def SquareMe(num):
    return num**2

您可以用任何数字(intfloatcomplex…)调用此函数

也可以这样做:

def MultMe(data):
    return data*2

这将适用于数字、字符串(!)、列表(!!)、NumPy数组以及任何可以与数字相乘的数组(如果某个类提供了此方法)。

在python中,你只需要创建一个方法,但你可以检查哪些参数可以被传递,如果它们是不同的参数(即:一个是float,另一个是int),那么你可以区分两个函数。在代码中,这看起来像:

def myfunc(*args):
# do something
# when you call the method
myfunc(a1, a2, k1=a3, k2=a4)
# you get: 
args = (a1, a2)
kwds = {'k1':a3, 'k2':a4}
#So now lets recreate myfunc to check arguments
def myfunc(*args):
    if isinstance(args[0], str): #This is where you determine argument type
        # do what you want to do if argument is string
    elif isinstance(args[1], int):
        # do what you want to do if argument is an int

正如ForceBru所说,Python并不真正关心参数类型,所以如果你关心,你可以自己处理:

def myfunc(x):
    if(isinstance(x,int)):
        print (x, 'int')  # as myfunc(int x)
    if(isinstance(x,float)):
        print (x, 'float') # as myfunc(float x)
myfunc(10) # 10 int
myfunc(10.2) # 10.2 float
myfunc ("A") # 

您可以让函数本身根据参数的类型和数量做不同的事情。

def f (a):
     if type (a) == 'float' or type (a) == 'int':
             ...
     if type (a) == 'list':
             ...
     if type (a) == 'dict':
             ...