I came across a problem for python decorator.
The question is:
Create a decorator which is responsible for multiplication of 2 numbers (say a,b), this multiplication of the numbers gives another number(say c).
Then needed to a create a actual function which does the summation of a,b and c.
Something like:
Decorator : a*b => c
Actual function: a+b+c
I have reached until this stage:
def my_decorator(func):
def addition(a,b):
c = a*b
return c
return addition
@my_decorator
def actual_func(a,b):
return a+b+c
But it gives error all the time.
>Solution :
Actual func
- Takes a, b and multiplies them
- decorator sums original numbers plus ouput of multiply func
Code
def my_decorator(func):
def addition(a,b):
c = func(a, b) # use multiplication function
return a + b + c # performs desired calculation
return addition # modified function for desired calculation
@my_decorator
def actual_func(a,b):
return a*b # does multiplication
actual_func(2, 4) # return 14 i.e. 2 + 4 + 2*4