有没有一种优雅的方法可以通过一个大功能来管理多个相关功能



编辑:
因为有些人显然误解了这个问题。。我甚至没有接近询问如何在python中进行切换/案例。请在投票支持关闭之前阅读。

我有n不同的函数,它们都高度相关,但参数略有不同
作为一个比喻,考虑它们代表n不同的排序算法。现在,我想要一个大的参数化函数sort,它从外部调用,然后在内部调用正确的排序算法/正确的函数
作为附加要求,必须能够为所有这些子函数提供不同的输入信息(不同数量的参数(

我想出了一个解决方案,但我觉得这是一种糟糕的风格。。有更多经验的人能对这个解决方案提出自己的想法吗?

def function_one(*args):
arg1, arg2 = args[0:2]
# do something here

def function_two(*args):
arg3, arg4 = args[2:4]
# do something here
# imagine that here are more functions
def function_n(*args):
arg1, arg3, arg5 = args[0], args[2], args[4]
# do something here
switcher = {
'one': function_one,
'two': function_two,
# ... imagine that here are more mappings
'n': function_n
}
def some_super_function(arg0, arg1=None, arg2=None, arg3=None, arg4=None, arg5=None, ..., argN=None):
return switcher.get(arg0)(arg1, arg2, arg3, arg4, arg5, ..., argN)

我没有看到根据传递的参数选择函数的要求,所以您可以传递一些参数来选择函数。

def function_one(*args):
print(f'run function_one, args - {args}')
# do something here

def function_two(*args):
print(f'run function_two, args - {args}')
# do something here

# imagine that here are more functions
def function_n(*args):
print(f'run function_n, args - {args}')
# do something here

switcher = {
'one': function_one,
'two': function_two,
# ... imagine that here are more mappings
'n': function_n
}

def some_super_function(func: str, *args):
return switcher[func](args)
some_super_function('one', 1, 2, 3) # run function_one, args - ((1, 2, 3),)
some_super_function('two', '12', 'asdasda', 11) # run function_two, args - (('12', 'asdasda', 11),)
some_super_function('n', [1, 2, 3], {1: 2}, [123, 321]) # run function_n, args - (([1, 2, 3], {1: 2}, [123, 321]),)

最新更新