What are Decorators in python
Published by
sanya sanya
In Python, a decorator is a special function that allows you to modify the behavior of another function without changing its source code. It is like adding an extra layer of functionality to an existing function, like putting a new coat of paint on a wall.
Imagine that you have a plain white wall in your house that you want to decorate. You could paint it a different color, but that would involve changing the wall's original structure. Instead, you decide to use a stencil to add a decorative pattern on top of the existing paint.
In Python, a decorator works in a similar way. It does not change the original function, but instead adds an extra layer of functionality on top of it. This can be useful when you want to add new features to an existing function without modifying its core functionality.
Let's look at an example to see how decorators work in practice:
def my_decorator(func): def wrapper(): print("Before function is called.") func() print("After function is called.") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello()
Output
Before function is called.
Hello!
After function is called.
In this example, we define a decorator function called **'my_decorator'**, which takes a function func as input and returns a new function wrapper. wrapper is defined inside ‘**my_decorator’ **and contains the extra functionality we want to add to func.
Next, we use the @my_decorator syntax to apply the 'my_decorator' decorator to the 'say_hello' function. This means that whenever 'say_hello' is called, it will be wrapped by 'my_decorator'.
When we call say_hello();, the decorator is executed first, printing "Before function is called." Then the original 'say_hello' function is called, which prints "Hello!". Finally, the decorator is executed again, printing "After function is called."
This example demonstrates how a decorator can add an extra layer of functionality to an existing function without modifying its core functionality. It is like adding a stencil to a plain white wall to create a decorative pattern without changing the original structure of the wall.
In Python, decorators can be used for a wide range of purposes, from logging and timing functions to authentication and authorization checks. For example, you could use a decorator to log the input and output of a function every time it is called, or to restrict access to a function based on user permissions.
In summary, decorators are a powerful tool for extending the functionality of Python functions. They allow you to add extra functionality to a function without changing its source code, making it easy to reuse and extend existing code. By using decorators.
Library
WEB DEVELOPMENT
FAANG QUESTIONS