Code Explanation:
1. Defining a Decorator
def dec(f):
def wrap(x=2): return f(x) + 5
return wrap
dec is a decorator factory.
It accepts a function f.
Inside it defines another function wrap:
wrap takes an argument x, defaulting to 2 if no value is passed.
It calls the original function f(x) and adds 5 to the result.
Finally, wrap is returned (replaces the original function).
2. Decorating a Function
@dec
def k(x): return x*3
Normally: def k(x): return x*3 defines a function.
Then @dec immediately wraps k with dec.
Effectively, after decoration:
k = dec(k)
So now, k is not the original function anymore. It is actually the wrap function returned by dec.
3. Calling the Decorated Function
print(k())
k() is actually calling wrap().
Since no argument is passed, wrap uses its default parameter x=2.
Inside wrap:
Calls the original k(2) (the old k before wrapping).
Original k(2) = 2*3 = 6.
Adds 5 → result = 11.
4. Output
11
Download Book - 500 Days Python Coding Challenges with Explanation


0 Comments:
Post a Comment