简体   繁体   中英

What's the correct way to handle function overloading with optional parameters?

This is what I want to achieve:

# first way to call. key value pair, where value could be anything.
def multiple_ways_to_call(key_param, value_param, optional = "optional"):
    pass

# second way to call. object_param is an instance of a specific class. type(object_param) == "myclass"
def multiple_ways_to_call(object_param, optional = "optional"):
    pass

I know function overloading isn't actually supported. I've done it before by just checking if last argument was null or not, but i'm not sure how to do it now that I have optional parameters.

How can I handle this scenario? I just the difference to be invisible to the caller.

There is the @singledispatch decorator in the functools module that was added in Python 3.4 - see Python Single Dispatch .

If you are on earlier versions of Python this was back ported and is available on PYPI .

The @singledispatch only differentiates based on the type of the first argument given to the function, so it is not as flexible as in some other languages.

Example from the docs:

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)

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