Function Decorators

Function Decorators

  • Decorator is a function which can take a function as argument and extend its functionality and returns modified function with extended functionality.
  • A decorator is a function that accepts a function as parameter and returns a function. A decorator takes the result of function, modifies the result and returns it.
  • The main objective of decorator functions is we can extend the functionality of existing functions without modifies that function.

Eg:

def wish(name):
        print("Hello",name,"Good Morning")

This function can always print same output for any name.
  • Hello Programmerfect Good Morning
  • Hello Richard Good Morning
  • Hello Rahul Good Morning
But we want to modify this function to provide different message if name is Rahul. We can do this without touching wish() function by using decorator. 

Note:

  • In the above program whenever we call wish() function automatically decor function will be executed.  

How to call same function with decorator and without decorator: 

  • We should not use @decor 

Eg 2:

with decorator we won't get any error. In this case output is:

We are dividing 20 with 2 
10.0 
We are dividing 20 with 0 
OOPS...cannot divide 
None

 

 

 


Comments