Search code examples
pythonpython-decorators

Python decorator for data analytics class


I need to create a decorator function that multiplies the input parameter of a function by ten before the function is called. Next, create a function called normal_function that takes an input value and displays the result. Test your decorator to ensure the displayed value is ten times larger than what was passed into normal_function.

def mult_decorator_function(a_normal_function):
  x = a_normal_function() * 10
  return x

@mult_decorator_function
def normal_function(x):
  print(x)

normal_function(10)

Solution

  • Have to have nested function for decorators, also need to have return instead of print:

    def mult_decorator_function(a_normal_function):
        def wrapper(x):
            x = a_normal_function(x) * 10
            return x
        return wrapper
    
    @mult_decorator_function
    def normal_function(x):
      return x
    
    print(normal_function(10))
    

    Output:

    100