In Python, a decorator is a function that takes another function as an argument and returns a new function. Decorators are defined using the @ symbol, followed by the name of the decorator function.
Here's an example of a simple decorator that adds some additional behavior to a function:
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 logging, timing, caching, authorization, validation, and error handling.
It's important to 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.