To define a decorator, the basic form is:
and to use this decorator, simply use:
In the sample code above:
func
: The function that the decorator is applied to.
my_func
.*args
, **kwargs
: The arguments of the function that the decorator is applied to.
foo='a', bar='b'
.Therefore, func(*args, **kwargs)
executes the original function. By using a decorator, we can insert logic before and after the function runs, which is essentially the concept of Aspect-Oriented Programming (AOP).
A decorator can modify the return value of the function it decorates. For example:
In this example, the decorator modify_return_decorator
modifies the return value of my_func
by prepending "Modified: " to it.
Decorators can also take arguments. To achieve this, you need an extra layer of function:
Decorators can also be applied to classes to modify or extend their behavior:
In this example, the class MyClass
is wrapped with additional functionality provided by the decorator.
By utilizing decorators, you can effectively implement AOP concepts in Python, allowing you to modularize cross-cutting concerns such as logging, authentication, and transaction management. Decorators provide a powerful and flexible way to extend and modify the behavior of functions and classes.