这就是我今天所做的;
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")
但在我看来,这是非常尴尬和丑陋的。该怎么办?
我可以创建某种“重载”装饰器等。但这不是我的代码的重点,我不想首先包含仅用于构造我的代码的函数。
我认为一个不太难看的方法是使用一个字典(下面代码中的
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)