Code Explanation:
Function Decorator Definition
def add(f):
This defines a decorator function named add.
It accepts another function f as its argument.
The purpose is to modify or extend the behavior of f.
Inner Wrapper Function
def w(x): return f(x) + 10
Inside add, a new function w(x) is defined.
This wrapper function:
Calls f(x)
Then adds 10 to its result
So, it modifies the original function’s output.
Returning the Wrapper
return w
The wrapper function w is returned.
So when add is used as a decorator, it replaces the original function with w.
Using the Decorator with @ Syntax
@add
def val(x): return x
The decorator @add is applied to the function val.
This is the same as:
def val(x): return x
val = add(val)
So, val(x) is now actually w(x), which returns x + 10.
Calling the Decorated Function
print(val(3))
val(3) is now w(3)
Inside w(3):
f(3) → original val(3) = 3
Then: 3 + 10 = 13
Final Output
13
The output of val(3) is 13, not just 3, because the decorator added 10 to it.
.png)

0 Comments:
Post a Comment