Decorators In Python

Decorators In Python

Decorator is a design pattern which is used for modifying existing objects without changing it. Functions in python are considered as first class objects, some properties of first class objects are as follows:

  • it can be stored as variables.
  • can have intrinsic¬†identity which means it is independent of any given name.
  • can be returnable as a result of function.
  • can be passed as argument to the function.

Lets us work on some few properties of decorators that are:

Assign Function to Variable

In python functions can be assigned to variables. Create a function name squared_number which takes one parameter as number and returns square of that number. Now we will assign this function to a variable return_square and use this variable to call a function, for example:

Passing Function as an Argument

We will take another example where we will pass function to argument of another function. Create a test function with one parameter as function name and create another function add which is passed as parameter to test function. Function add takes one argument as integer and return an integer after adding 3 to it, for example:

Return Function Result as Function

In python function can also return another function let us take this example, we will define a square function which will return a square of any number. Again we will define another function square_wrapper which will return square function as a result, for example

so in above example you can see that while calling square function it will prints the square value of any number but when we call square_wrapper function it will return square function result and also prints the string inside wrapper function.

Working With Decorators in Python

Lets start working with decorators, create a function add which will add two numbers and prints the result.

As shown in above script, then we will create a function addAndSubstract which will use to decorate add function. Function addAndSubrtract accepts one parameter as function and returns the wrapper function, this wrapper function takes same parameter as add function and return addition as well as substraction result. We can decorate add function using @addAndSubstract and also we can call it as a function with add as a parameter. you can learn more about different design patterns in this link.

Leave a Comment