ank
ank

Reputation: 33

Called a decorator's returned value -- Python

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

Answers (2)

DarrylG
DarrylG

Reputation: 17156

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 

Upvotes: 1

Akida
Akida

Reputation: 1116

Please include your error in the question.

Your current state looks promising but there are small mistakes:

  • the inner function (addition) should call func with the correct arguments (a,b,c) and return its return value
  • actual_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

Related Questions