简体   繁体   中英

Function signature in python

In C++ two functions with the same name can be created as long as the signature is different. So for example myfunc(int x) is different from myfunc(float x) . In python you cannot do this, so, do you need to define functions with different names, or is there a better way to handle this situation?

In Python3.4+ you can use the functools.singledispatch decorator, which allows you to define a generic function and then register typed implementations against it.

From the docs

Generic function:

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

Typed functions:

>>> @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)

There's no built-in solution for earlier releases of Python, but Guido van Rossum blogged about a solution for python2 using decorators. (Edit: there is also a backport of the 3.4 functionality for pythons 2.6 - 3.3 on pypi )

Edit: Of course, one of the advantages of using Python is that the the same code can often handle ints and floats without explicit dispatching on type, which is one of the reasons why the functionality has only recently been added.

Python doesn't really care whether an argument is an integer or a float. It's dynamically typed . You can do, for example, this:

def SquareMe(num):
    return num**2

And you can call this function with any number.

It's also possible to do this:

def MultMe(data):
    return data*2

This will work with numbers, strings (!), arrays (!!) and anything that can be multiplied by a number (if some class provides a method for this).

In python, you have to create only one method, but you can check what arguments can get passed, and if they are different arguments (ie: one is a float and another is an int) then you can differentiate two functions. In code this would look like:

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

As ForceBru said Python dosen't realy care about parameter type , so if you do , you can handle it yourself:

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") # 

You could have the function itself do different things based on the types and number of parameters.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM