passing functions and its arguments to another function

后端 未结 3 1718
醉话见心
醉话见心 2021-01-16 15:38

I have tree types of sub-functions:

  • one without any parameters (arguments),
  • second with one parameter
  • third with multiple parameters (tuple
3条回答
  •  猫巷女王i
    2021-01-16 16:11

    Something like this would work:

    def no_arg():
        return 5
    
    def one_arg(x):
        return x
    
    def multiple_args(x, y):
        return x * y
    
    def function_results_sum(*args, **kwargs):
        result = 0
        for func in args:
                result += func(*kwargs[func.__name__])
        return result
    

    Output:

    function_results_sum(
        no_arg, one_arg, multiple_args,
        no_arg=(),
        one_arg=(23, ),
        multiple_args=(1,5))
    
    33
    

    The only difference between what you are asking is that you have to put args in a tuple to then unpack as args to pass in later.

    If you dont want to have to supply anything for no argument functions, you can double check if the func name is in kwargs:

    def function_results_sum(*args, **kwargs):
        result = 0
        for func in args:
            if func.__name__ i kwargs:
                result += func(*kwargs[func.__name__])
            else:
                result += func()
        return result
    

提交回复
热议问题