Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading