def log(func): def decorated(*args, **kwargs): print(f"Called with arguments: {args}, {kwargs}") result = func(*args, **kwargs) print(f"Return value: {result}") return result return decorated
To make a function decorator in Python, you need to define a function that takes a function as an argument and returns a modified version of that function. The modified version of the function is often called the "decorated" version of the function.
This decorator can be used to decorate any function by adding the @log decorator above the function definition, like this:
@log def add(x, y): return x + y
@log @another_decorator @yet_another_decorator def add(x, y): return x + yIn this example, the add function will be decorated by all three decorators, in the order that they are listed. This means that the another_decorator will be applied first, then yet_another_decorator, and finally the log decorator. The order in which the decorators are applied is important, as it determines the order in which they will modify the behavior of the decorated function.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.