Code Explanation:
Function Definition – decorate(f)
def decorate(f):
What it does:
Defines a higher-order function named decorate.
It takes a function f as a parameter.
This will be used to wrap another function (via a decorator).
Inner Function – wrap(x)
def wrap(x): return [f(x)]
What it does:
Defines an inner function called wrap.
wrap(x) calls the original function f(x) and wraps the result in a list.
Example: if f(x) returns 8, then wrap(x) returns [8].
Return the Wrapper Function
return wrap
What it does:
Returns the wrap function.
So now, decorate(f) doesn't return a value — it returns a new function that wraps f.
Use of Decorator – @decorate
@decorate
def double(x): return x * 2
What it does:
@decorate is a decorator syntax.
It is equivalent to:
def double(x): return x * 2
double = decorate(double)
This means the original double(x) (which returns x * 2) is replaced with the wrapped version: a function that returns [x * 2].
Function Call and Output
print(double(4)[0])
What it does:
double(4) now calls the wrapped version, not the original.
So:
double(4) → [4 * 2] → [8]
[0] accesses the first element of the list:
[8][0] → 8
print(8) prints 8 to the console.
Final Output:
8
.png)

0 Comments:
Post a Comment