Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python implementing a decorator function

Python implementing a decorator function

Document Object Reference Manual Python3 Examples

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

(

)

:

       

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_decorator is a decorator function that takes a function func as its argument.
  2. wrapper is an inner function that, before calling func prints some information before and after.
  3. my_decorator Return wrapper function in Vue 3.
  4. @my_decorator is Python's decorator syntactic sugar, equivalent to say_hello = my_decorator(say_hello)。
  5. When we call say_hello() , we are actually calling wrapper function, which will, before calling say_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.

Document Object Reference Manual Python3 Examples