Code Explanation:
Line 1: def dec(f):
Defines a decorator function named dec. The parameter f receives the original function that we want to modify.
Line 2: cache = {}
Creates an empty dictionary to store how many times each argument has been passed to the decorated function.
Initially:
cache = {}
Line 3: def wrap(x):
Defines an inner function named wrap. This function replaces the original function's name after the decorator is applied.
Line 4: cache[x] = cache.get(x, 0) + 1
This line updates the call count for argument x.
- cache.get(x, 0) returns the existing count, or 0 if x is not present.
- + 1 increases that count by one.
- cache[x] = saves the updated count.
For x = 3, the first call stores 3: 1; the second call updates it to 3: 2.
Line 5: return f(x) + cache[x]
Calls the original function using f(x) and adds the current count from the dictionary.
For x = 3:
- f(3) returns 3 * 2 = 6.
- On the first call, cache[3] is 1, so the result is 6 + 1 = 7.
- On the second call, cache[3] is 2, so the result is 6 + 2 = 8.
Line 6: return wrap
Returns the inner function wrap instead of executing it immediately. The dictionary remains accessible to wrap through a closure.
Line 7: @dec
Applies the decorator to calc. It is equivalent to writing:
calc = dec(calc)
After decoration, the name calc refers to the wrapper function.
Line 8: def calc(x):
Defines the original function that receives the argument x.
Line 9: return x * 2
Returns twice the value of x. For x = 3, the original function returns 6.
Line 10: print(calc(3), calc(3))
Calls the decorated function twice with the same argument, 3.
- First call returns 7.
- Second call returns 8.
- print() displays both values separated by a space.
4. Final Output
7 8


0 Comments:
Post a Comment