简体   繁体   中英

Pass a function that accepts multiple arguments as an argument to a function

I'm studying how to pass a function as an argument. I've encountered a problem where I tried to invoke a passed-in function which accepts multiple arguments.

Code:

    def add(*numbers):
        total = 0
        for number in numbers:
            total += number
        return total

    def apply(func, value):
        return func(value)


    print(apply(add, (1,2,3)))

Output:

    Traceback (most recent call last):
      File "D:\PythonPrac\test.py", line 13, in <module>
        print(apply(add, (1,2,3)))
      File "D:\PythonPrac\test.py", line 9, in apply
        return func(value)
      File "D:\PythonPrac\test.py", line 4, in add
        total += number
    TypeError: unsupported operand type(s) for +=: 'int' and 'tuple'

Thanks again!

you are summing up an integer to a tuple:

0 + (1,2,3)

so when you call it you have to do this:

add(1,2,3)

or you have to change the add function in this way:

def add(numbers):
        total = 0
        for number in numbers:
            total += number
        return total

so in this case you iterate trough number that is a tuple: (1,2,3) and not a list of tuple like before: [(1,2,3)]

then, it might be a stupid question because you can have your reasons (and maybe it wil be better to you to explain them) but why do you do:

apply(add, (1,2,3))

instead of:

add((1,2,3)) or add(1,2,3) (it depends if you use your or my version of the add function)

it appear like a nonsense thing that you use a function that ONLY calls another function instead of calling it directly

finally if you want to do it in your way you have to do:

def add(*numbers):
        total = 0
        for number in numbers[0]:
            total += number
        return total

Have removed asterisk * from numbers in add Function

       def add(numbers):
           total = 0
           for number in numbers:
              total += number
           return total

       def apply(func, value):
          return func(value)  

Add an asterisk before values on line 8.

def add(*numbers):
    total = 0
    for number in numbers:
        total += number
    return total

def apply(func, value):
    return func(*value)


print(apply(add, (1,2,3)))

Explenation: This unpacks the tuple as arguments, so the evalution will be roughly like this:

apply(add, (1, 2, 3))
add(*(1, 2, 3))
add(1, 2, 3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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