Code Explanataion:
๐งฉ 1. Decorator Function Definition
def decorator(func):
Defines a function named decorator.
It takes another function (func) as an argument.
This is the core idea of decorators: functions that modify other functions.
๐ 2. Wrapper Function Inside Decorator
def wrapper():
A nested function wrapper is defined.
This function will replace/extend the behavior of func.
✖️ 3. Modify Original Function Output
return func() * 2
Calls the original function func().
Multiplies its result by 2.
Returns the modified value.
๐ 4. Return Wrapper Function
return wrapper
The decorator returns the wrapper function.
This means the original function will be replaced by wrapper.
๐ฏ 5. Applying the Decorator
@decorator
This is syntactic sugar for:
say = decorator(say)
It passes say into decorator and replaces it with wrapper.
๐ฆ 6. Original Function Definition
def say():
return 5
A simple function that returns 5.
But due to the decorator, this function will not run directly.
๐ 7. What Actually Happens Internally
After decoration:
say = decorator(say)
Now say actually refers to wrapper.
When you call say(), it calls wrapper().
๐จ️ 8. Function Call and Output
print(say())
Execution Flow:
say() → actually calls wrapper()
wrapper() → calls original func() → returns 5
5 * 2 = 10
✅ Final Output
10

0 Comments:
Post a Comment