def make_box_volume_function(height):
# defines and returns a function that takes two numeric arguments,
# length & width, and returns the volume given the input height
def volume(length, width):
return length*width*height
return volume
box_volume_height15 = make_box_volume_function(15)
print(box_volume_height15(3,2))
I was trying a different way of writing this. If I send all 3 arguments in the main function, it print the memory of the function. what can I change to get the volume instead
def make_box_volume_function(height,length,width):
# defines and returns a function that takes two numeric arguments,
# length & width, and returns the volume given the input height
def volume():
return length*width*height
return volume
box_volume_height15 = make_box_volume_function(15,3,2)
print(box_volume_height15)
The output is
<function make_box_volume_function..volume at 0x0000020C52CB2310>
If that is logged out, then perhaps you haven’t invoked it yet to get the expected output?
At this point you are returning a function, not a computed value.
We need to take a close look at what your ‘make_box_volume_function’ is doing. It is returning a function. However, the way it is represented above (in your code) that function will never work. There are no parameters and the local variables (in your code) have not been defined.
What is suggested in this amounts to a function that will take some parameters and make them constant in the returned function, leaving a placeholder for the mystery variable.
Let’s shorten some names for clarity:
m = make_box_volume_function
l = length
w = width
h = height
Now function m will return, let’s say, a function to compute volume by height with the constants of length and width:
def m (l, w):
def f (h):
return l * w * h
return f
Now if we were to say that all grain elevators are 60 feet by 80 feet, we can feed this information to our function factory and have it yield a function to compute volume by height of all our elevators.
It would appear that one of the goals of function factories is to abstract away the constraints so the returned function can be more simplified and specific. A function with one argument runs faster than one with two, and so on. We can make excellent use of these constructs, especially in optimized environments where we throw away everything once consumed. It is a chapter on optimization, by itself. Iterators aren’t the only things we consume.