繁体   English   中英

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

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

这是我要实现的目标:

# 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

我知道实际上不支持函数重载。 我以前只是通过检查最后一个参数是否为null来完成此操作,但是由于我有可选参数,因此我不确定如何执行此操作。

如何处理这种情况? 我只是呼叫者看不见的区别。

在Python 3.4中添加了functools模块中的@singledispatch装饰器-请参阅Python Single Dispatch

如果您使用的是Python的早期版本, 则将其反向移植,并在PYPI上可用

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

暂无
暂无

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

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