Advanced Lesson 4
Python Decorators
Chapter 1: Introduction
Returning a function
You can also return a function.
Remember, you are returning a function (func
), not the output of a function call (func()
)!
Make sure you understand how x
and n
are used in the example below!
1 2 3 4 5 6 7 8 9 10 11 |
|
Line 7 calls the function power()
with argument n=2
. This function returns its inner function nth_power
(but does not call this function). Lines 2 and 3 are part of a function definition, so are not yet executed since the function has not been called.
The variable squarer
points to the nth_power
function that was returned by power(2)
, so calling squarer()
is equivalent to calling nth_power()
. So Line 8 calls nth_power()
with the argument x=5
. Since n
has been set to 2
earlier, the function will compute 5**2
, and return 25
.
The same goes for Lines 10-11.
Make sure you understand everything we have discussed so far before moving on. Otherwise it will get really confusing!