A decorator can be simply understood as a decoration, adding additional functions to a function, but without modifying the code of the original function, just use @ syntax sugar in front of the original function definition. It is often used to insert logs and other similar scenarios, and can be reused without modifying the main function code.
Look at the first example: a function
def printName(): print('LiHaiyu') printName()
Output: LiHaiyu
Look at the second example: simple decorator function
def mydecorator(f): def wrapper(): # define the decorator function print('Before calling the function') f() print('After calling the function') return wrapper #Note that the return function forms a closure @mydecorator def printName(): print('LiHaiyu') printName()output:
Reminder: @mydecorator must be placed before the definition of the decorated function. Equivalent to passing the printName function to the decorator function, and executing the decorator function when printName() is called.
The third example: function with parameters
def mydecorator(f): def wrapper(*args, **kwargs): print('Before calling the function') f(*args, **kwargs) print('Before calling the function') return wrapper @mydecorator def printName(name): print(name) printName("LiHaiyu")
output: same as above
Reminder: *args means passing a list parameter, **kwargs means passing a dictionary parameter. So you should also pass parameters when calling the function
Fourth example: decorator with parameters
def mydecorator(msg = 'Message'): def decorated(f): def wrapper(*args,**kwargs): print('The message is : '+ msg) print('Before calling the function') f(*args,**kwargs) print('After calling the function') return wrapper return decorated @mydecorator(msg = 'print name') def printName(name): print(name) printName('LiHaiyu')
output:
Reminder: return function
Reference link: https://www.youtube.com/watch?v=mZ5IwFfqvz8