Function Decorators:

To understand decorator functions, we should know the following about functions in Python:

  • A function can be defined inside another function in Python.
  • A function can be passed as another function in Python.

Function Decorator:

A function that takes a function as its only parameter and returns a function is known as a decorator. It is very useful when we have to “wrap” functionality with the same code again ad again.

To specify a decorator to be applied to another function, we use @func_name.

Decorators can also be used for attachment of data( or adding attribute) to functions.

In the above example when add.data is called, then the add function is passed into another decorator function ‘attach_data’ as an argument, and this returns ‘add’ function with an attribute ‘data’ which is set to 3, and hence printing takes place.

The decorators can also be used for the removal of redundancies.

Leave a Reply

Your email address will not be published. Required fields are marked *