Lets say we have two defined function objects
add1 = lambda x: x+1
and
square = lambda x: x*x
now I want to have a function that calls and adds the result of these two functions.
What I thought would work is:
def addFuncs(f,g):
f+g
addFuncs(add1,square)(10)
Which I thought would give me an answer of 111 (10*10 + 10+1)
But that just gave me an error TypeError: unsupported operand type(s) for +: 'function' and 'function'
So I tried:
def addFunctions(f, g):
def getf():
return f
def getg():
return g
return getf() + getg()
But still to no avail…
However, if I do
def addFunctions(f, g):
return f
it pops out with 100, so it seems to evaluate the function on return, But I can’t figure out how to get it to evaluate the functions first and then operate on them.
Any help would be greatly appreciated!
EDIT
Got it!
def addFunctions(f, g):
return lambda x: f(x) + g(x)
Python doesn’t support adding functions together which both of your attempts tried to do. Instead, you need to create a new function, such as with lambda which calls the original functions.