Code Explanation:
1. Defining the Decorator negate
def negate(f):
def w(x): return -f(x)
return w
negate(f) is a decorator function.
It takes a function f as input.
Inside it, w(x) is defined, which:
Calls f(x) (the original function),
Negates its result (i.e., multiplies it by -1).
Finally, it returns the wrapper function w.
Purpose: This decorator flips the sign of any function’s output.
2. Applying the Decorator with @negate
@negate
def pos(x): return x + 5
This is shorthand for:
def pos(x): return x + 5
pos = negate(pos)
So, the original pos(x) which returned x + 5 is now wrapped.
The wrapped version will return -(x + 5) instead.
3. Calling the Decorated Function
print(pos(3))
This calls the decorated version of pos with input 3.
Internally:
pos(3) → w(3) → -f(3) → -(3 + 5) → -8
Final Output
-8
.png)

0 Comments:
Post a Comment