Code Explanation:
1) Defining the Decorator
def dec(f):
dec is a decorator that takes a function f as an argument.
The purpose is to wrap and modify the behavior of f.
2) Defining the Wrapper Function
def wrap(*args, **kwargs):
return f(*args, **kwargs) + 10
wrap accepts any number of positional (*args) and keyword (**kwargs) arguments.
Inside wrap:
Calls the original function f with all passed arguments.
Adds 10 to the result of f.
3) Returning the Wrapper
return wrap
dec(f) returns the wrap function, which replaces the original function when decorated.
@dec
def g(x, y): return x*y
4) Decorating the Function
@dec is equivalent to:
g = dec(g)
Now g is actually the wrapper function returned by dec.
When you call g(2,3), you are calling wrap(2,3).
print(g(2,3))
5) Calling the Decorated Function
wrap(2,3) executes:
f(2,3) → original g(2,3) = 2*3 = 6
Add 10 → 6 + 10 = 16
Output
16
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment