Code Explanation:
1️⃣ Creating the Decorator Function
def dec(f):
dec() is a decorator function.
It receives another function as its argument.
Here, f will eventually refer to the square function.
2️⃣ Creating the Wrapper Function
def wrapper(x):
Inside dec(), another function named wrapper is created.
This function accepts one argument, x.
The purpose of wrapper() is to modify or extend the behavior of the original function.
3️⃣ Calling the Original Function
return f(x) * 2
First:
f(x)
calls the original function.
Since f will refer to square:
f(4)
is equivalent to:
square(4)
The square() function returns:
4 + 1 = 5
Then the decorator multiplies that result by 2:
5 * 2 = 10
So wrapper(4) returns:
10
4️⃣ Returning the Wrapper
return wrapper
The decorator returns the wrapper function.
This means the original square function will be replaced by the returned wrapper.
Conceptually:
square = dec(square)
5️⃣ Applying the Decorator
@dec
This is decorator syntax.
It tells Python:
square = dec(square)
So square is passed into dec().
Inside dec():
f → original square()
and the function returned is:
wrapper
Therefore, after decoration, square refers to wrapper.
6️⃣ Defining the Original Function
def square(x):
This defines the original function named square.
It accepts one argument, x.
7️⃣ Returning x + 1
return x + 1
Notice that despite the name square, this function does not actually calculate a square.
For:
square(4)
the original function would return:
4 + 1 = 5
But because of the decorator, the final result is modified.
8️⃣ Calling square(4)
print(square(4))
After decoration, square actually refers to wrapper.
So this effectively becomes:
wrapper(4)
Inside wrapper():
f(4) * 2
The original function produces:
4 + 1 = 5
Then:
5 × 2 = 10
๐ Complete Execution Flow
@dec
↓
square = dec(square)
↓
wrapper is returned
↓
square(4)
↓
wrapper(4)
↓
original square(4)
↓
4 + 1 = 5
↓
5 × 2
↓
10
๐ฏ Final Output
10

0 Comments:
Post a Comment