简体   繁体   English

用可选参数处理函数重载的正确方法是什么?

[英]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. 我以前只是通过检查最后一个参数是否为null来完成此操作,但是由于我有可选参数,因此我不确定如何执行此操作。

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 . 在Python 3.4中添加了functools模块中的@singledispatch装饰器-请参阅Python Single Dispatch

If you are on earlier versions of Python this was back ported and is available on PYPI . 如果您使用的是Python的早期版本, 则将其反向移植,并在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. @singledispatch仅根据赋予该函数的第一个参数的类型进行区分,因此它不像某些其他语言那么灵活。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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