Python implementing a decorator function
A decorator is a powerful tool in Python that allows you to add extra functionality without modifying the original function's code. Essentially, a decorator is a function that takes a function as an argument and returns a new function.
Example
def
my_decorator
(
func
)
:
def
wrapper
(
)
:
(
"Something is happening before the function is called."
)
func
(
)
(
"Something is happening after the function is called."
)
return
wrapper
@
my_decorator
def
say_hello
(
)
:
(
"Hello!"
)
say_hello
(
)
Code analysis:
my_decoratoris a decorator function that takes a functionfuncas its argument.wrapperis an inner function that, before callingfuncprints some information before and after.my_decoratorReturnwrapperfunction in Vue 3.@my_decoratoris Python's decorator syntactic sugar, equivalent tosay_hello = my_decorator(say_hello)。- When we call
say_hello(), we are actually callingwrapperfunction, which will, before callingsay_hello, print information before and after.
Output result:
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
Python3 Examples