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 def add_numbers(a, b): return a + b
Comments
Post a Comment