Code Explanation:
Decorator Function Definition
def dec(f):
def wrap(x): return f(x) + 1
return wrap
Explanation:
dec(f) is a decorator that:
Wraps a function f
Calls f(x) and adds 1 to the result
The inner function wrap does the actual wrapping logic.
It returns wrap, effectively replacing the original function.
First Definition of num (Decorated)
@dec
def num(x): return x * 2
Explanation:
This is equivalent to:
def num(x): return x * 2
num = dec(num) # num now points to wrap(x)
So num(2) at this point would compute:
x * 2 = 4
Then wrap adds 1 → 4 + 1 = 5
Second Definition of num (Overrides the First!)
def num(x): return x * 3
Explanation:
This redefines the num function.
The decorated version (num = dec(...)) is overwritten.
So the decorator is now completely discarded.
Now, num(2) → 2 * 3 = 6
Function Call and Output
print(num(2))
Explanation:
Calls the second version of num (not decorated).
So output is simply:
2 * 3 = 6
Final Output:
6
.png)

0 Comments:
Post a Comment