Code Explanation:
1. Define a Decorator Function
def decorator(f):
def wrapper(x):
return f(x) + 1
return wrapper
decorator is a higher-order function: it takes a function f as input.
Inside it, wrapper(x) is defined, which:
Calls the original function f(x).
Adds 1 to the result.
wrapper is returned — this becomes the new version of the function.
2. Apply Decorator Using @ Syntax
@decorator
def f(x):
return x * 2
This is syntactic sugar for:
def f(x):
return x * 2
f = decorator(f) # f now refers to wrapper(x)
So f is now replaced by wrapper(x).
3. Call the Decorated Function
print(f(3))
Since f is now wrapper, here's what happens:
wrapper(3) is called.
Inside wrapper:
f(3) is evaluated as 3 * 2 = 6.
6 + 1 = 7 is returned.
Final Output
7
.png)

0 Comments:
Post a Comment