What is a decorator in Python, and how does it work?

What is a decorator in Python, and how does it work?

A: A decorator is a design pattern in Python that allows you to modify the behavior of a function or class without changing its source code directly. Decorators are used to add new features to an existing function or class, such as logging, caching, or authentication.

In Python, decorators are implemented as functions that take another function or class as an argument and return a new function or class that wraps the original one. This new function or class can then modify the behavior of the original function or class in some way.

For example, here's a simple decorator that adds logging to a function:

python

def log_decorator(func): def wrapper(*args, **kwargs): print(f"Calling function {func.__name__}") result = func(*args, **kwargs) print(f"Function {func.__name__} returned {result}") return result return wrapper @log_decorator def add_numbers(a, b): return a + b

In this example, the log_decorator function takes another function (func) as an argument and returns a new function (wrapper) that wraps the original function. The wrapper function adds logging before and after calling the original function.

The @log_decorator syntax is a shorthand for applying the log_decorator to the add_numbers function. When we call add_numbers(2, 3), the log_decorator is automatically applied to the function, and we get the following output:

javascript

Calling function add_numbers Function add_numbers returned 5

This is just one example of how decorators can be used in Python. They are a powerful tool for adding functionality to existing code and can be used in many different ways.

Comments

Popular posts from this blog

What is Microsoft SharePoint ?

General Cybersecurity

Well-Architected Framework | Solution Architect