Know more about Decorators in Python
let’s understand what is decorators in python and how it work …
- Decorators are evolved from the concept of closures.
- A decorator function is a higher order function that takes a function as an argument and returns the inner function.
- A decorator is capable of adding extra functionality to an existing function, without altering it.
- The decorator function is prefixed with
@
symbol and written above the function definition.
Consider the below three examples:
I. First one shows the creation of closure function wish
using the higher order function outer
.
II. The second one shows the creation of decorator function outer
, which is used to decorate function sayHello
. This is achieved with a small change to Example1
.
III. Third one displays decorating the sayHello
function with decorator function, outer
, using @
symbol.
Example 1 .
wish
is the closure function obtained by calling an outer function with the argumentsayHello
.- When
wish
function is called,inner
function gets executed.
Output
Accessing : sayHello
Hello!
Example 2:
Output
Accessing : sayHello
- The function returned by
outer
is assigned tosayHello
i.e the function name passed as argument toouter
. - This makes
outer
a decorator tosayHello
. - In Python, decorating a function can also be achieved by writing decorator function name, prefixed with
@
symbol, just above the function to be decorated. - Hence,
sayHello = outer(sayHello)
expression is same as@outer
.
Example 3:
Output
Accessing : sayHello
Conclusion
The intent of this article is to give you enough information about python decorators through examples.