Function Decorators With Parameters
In this example, we create a decorator that will multiply a value returned by a 2 parameters func by a value.
What we want to achieve
- Suppose you have a decorator and a function like the following:
1@mult(5)
2def add_nums(a,b):
3 return a+b
- The idea is that instead of having add_nums(3,4) return 7, it will return 35.
It makes our function multiply the result by 5. - Note, that for a decorator to work, it need not be called, it is just a reference to a decorator function that can enhance our target function.
- In other words:
- mult is not a decorator
- mult(5) return a decorator
- this returned decorator will be called by @ operator to replace add_nums func.
A function to create a decorator
- Look at the following structure:
1def mult(num):
2 def mult_decorator(two_params_func):
3 def new_two_params_func(a,b):
4 temp = two_params_func(a,b)
5 return temp * num
6 return new_two_params_func
7 return mult_decorator
- The mult function IS NOT THE DECORATOR!
- Calling mult(5) returns the internal mult_decorator WHICH IS THE DECORATOR!
- The decorator is then called by python @ itself.
It then returns the enhanced 2 parameter function.