Decorators are a powerful feature of Python that allows you to modify the behavior of functions or classes without changing their source code. A decorator is a function that takes another function as an argument and returns a new function that adds some additional functionality to the original function.
In Python, a decorator is denoted by the @ symbol followed by the decorator function name, which is placed just before the function to be decorated.
Here's an example of a simple decorator:
def my_decorator(func): def wrapper(): print("Before function call") func() print("After function call") return wrapper@my_decoratordef say_hello(): print("Hello, World!")say_hello() |
In the above example, my_decorator is a function that takes another function func as its argument and returns a new function wrapper. wrapper adds some additional functionality to func by printing a message before and after it is called. The @my_decorator decorator is applied to the say_hello function, which is then passed to the my_decorator function as an argument. When say_hello is called, it is actually calling the wrapper function returned by my_decorator, which in turn calls the original say_hello function and adds some additional behavior.
The output of the above code will be:
Before function callHello, World!After function call |
Decorators can be used to implement a variety of functionality, including:
Decorators can also be stacked, allowing you to apply multiple decorators to a single function.
Note that decorators can make code harder to read and debug, so they should be used with care and only when they simplify code structure and improve code reusability.