Python implements a decorator function

Document 对象参考手册Python3 Examples

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()

Code analysis:

  1. my_decoratoris a decorator function that accepts a functionfuncas an argument.
  2. wrapperis an inner function. When callingfuncit prints some information before and after respectively.
  3. my_decoratorReturnwrapperfunction.
  4. @my_decoratoris Python's decorator syntactic sugar, equivalent tosay_hello = my_decorator(say_hello)。
  5. When we callsay_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.

Document 对象参考手册Python3 Examples

Other extensions