Reputation: 33
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.
Upvotes: 0
Views: 150
Reputation: 17156
Actual 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
Upvotes: 1
Reputation: 1116
Please include your error in the question.
Your current state looks promising but there are small mistakes:
addition
) should call func
with the correct arguments (a,b,c
) and return its return valueactual_func
should add the three numbers and needs to take these three as parameters. Else c
is not defined in actual_func
.Complete code:
def my_decorator(func):
def addition(a,b):
c = a*b
return func(a,b,c)
return addition
@my_decorator
def actual_func(a,b,c):
return a+b+c
Upvotes: 0