What are Python decorators and how do they work?
Decorators are functions that modify the behavior of another function or method. They allow you to wrap another function and add functionality.
Decorators are a powerful feature in Python that allows you to modify or extend the behavior of functions or methods without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function that usually enhances or alters the behavior of the original function.
Here’s how you can create a simple decorator:
def my_decorator(func):
def wrapper():
print('Before the function is called.')
func()
print('After the function is called.')
return wrapper
You can then apply this decorator to a function using the @
symbol:
@my_decorator
def say_hello():
print('Hello!')
When you call say_hello()
, the output will include messages before and after the original function’s execution. This technique is useful for adding functionality such as logging, timing, or access control to existing functions without modifying their code directly. Decorators can also take arguments, making them even more flexible. By understanding and utilizing decorators, you can write cleaner and more reusable code.