如何根据参数数量选择我的函数[重复]

问题描述 投票:0回答:1

我知道Python中不乏关于函数重载的问题,但我不认为它们解决了我的问题。

这就是我今天所做的;

def some_function_with_one_argument(x): ...

def almost_the_same_function_but_with_two_arguments(x, y): ...

def same_again_but_now_with_three_arguments(x, y, z): ...

def some_function(*args):
    match len(args):
        case 1:
            return some_function_with_one_argument(*args)
        case 2:
            return almost_the_same_function_but_with_two_arguments(*args)
        case 3:
            same_again_but_now_with_three_arguments(*args)
        case _:
            raise TypeError(f"some_function() takes between one and three positional arguments but {len(args)} were given")

但这在我看来是超级尴尬和丑陋的。

Python 诸神似乎不希望你做任何类似于函数重载的事情,即使它很有意义,那么该怎么办呢?

当然,我可以创建某种“重载”装饰器等,但这不是我的代码的重点,我真的不想用不相关的函数污染我的代码,这些函数首先只用于构造我的代码.

python overloading dispatch
1个回答
1
投票

我认为一个不太难看的方法是使用一个字典(下面代码中的

function_mapper
)将参数数量映射到函数引用,然后你可以调用一次
function_mapper[len(args)](*args)
。这样代码会更短,并且您不必从匹配案例中显式调用每个函数

def some_function_with_one_argument(x): ...

def almost_the_same_function_but_with_two_arguments(x, y): ...

def same_again_but_now_with_three_arguments(x, y, z): ...

def some_function(*args):
    function_mapper = {
        1: some_function_with_one_argument,
        2: almost_the_same_function_but_with_two_arguments,
        3: same_again_but_now_with_three_arguments
    }

    if len(args) not in function_mapper:
        raise TypeError(f"some_function() takes between one and three positional arguments but {len(args)} were given")
    else:
        function_mapper[len(args)](*args)

© www.soinside.com 2019 - 2024. All rights reserved.