Code Explanation:
1. Defining the decorator function
def dec(f):
Here, dec is a decorator function that takes another function f as its argument.
A decorator is a function that modifies the behavior of another function.
2. Defining the wrapper function inside dec
def wrap(x):
print("Wrapped!")
return f(x)
Inside dec, we define another function wrap.
wrap takes one argument x.
It first prints "Wrapped!".
Then it calls the original function f(x) and returns its result.
So this wrap function adds extra behavior (printing) before calling the actual function.
3. Returning the wrapper
return wrap
Instead of returning the original function, dec returns the modified wrap function.
This means: when dec is used, the original function is replaced by wrap.
4. Decorating function g
@dec
def g(x): return x**2
@dec is shorthand for:
g = dec(g)
So the function g(x) (which normally just does x**2) is wrapped by the decorator.
Now, calling g(x) really means calling wrap(x).
5. Calling g(4)
print(g(4))
Since g was decorated, g(4) calls wrap(4).
Step by step:
"Wrapped!" is printed.
Then the original g(4) → 4**2 = 16 is computed.
That result (16) is returned to print.
Final Output
Wrapped!
16
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment