When you create a decorator, the decorator function is called with the original function as its argument. This means that you have access to the original function inside the decorator, and you can modify its behavior in any way you want.
Here's an example of a decorator that modifies the behavior of the original function:
def my_decorator(func): def wrapper(*args, **kwargs): print("Before function call") result = func(*args, **kwargs) print("After function call") return result return wrapper |
In this example, the my_decorator function takes a function as its argument and returns a new function wrapper that wraps the original function with additional behavior. When the new function is called, it prints "Before function call", calls the original function with the given arguments, prints "After function call", and returns the result.
To use this decorator with a function, simply apply it to the function:
@my_decoratordef my_function(): print("Function call") |
In this example, the @my_decorator syntax applies the my_decorator decorator to the my_function() function. When the function is called, the decorator will add the behavior of printing "Before function call" and "After function call" around the function call.
Inside the wrapper function, you have access to the original function func, which you can call with the given arguments. This allows you to modify the behavior of the original function in any way you want. You can also pass additional arguments to the wrapper function and use them to modify the behavior of the original function.
Using a decorator to modify the behavior of a function can be useful when you need to add additional behavior to a function without modifying its code. It allows you to keep the original function intact and add behavior on top of it, making it easier to maintain and modify.