Python implements a decorator function
A decorator is a powerful tool in Python that allows you to add extra functionality without modifying the original function code. A decorator is essentially a function that takes a function as an argument and returns a new function.
Example
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Code analysis:
my_decoratoris a decorator function that accepts a functionfuncas an argument.wrapperis an inner function. When callingfuncit prints some information before and after respectively.my_decoratorReturnwrapperfunction.@my_decoratoris Python's decorator syntactic sugar, equivalent tosay_hello = my_decorator(say_hello)。- When we call
say_hello()it actually callswrapperfunction, which willsay_helloprint information before and after.
Output:
Something is happening before the function is called. Hello! Something is happening after the function is called.Other extensions
Python3 Examples