The role of decorators
The function of the python function decorator @ is to add additional functions to existing functions, which are often used for log insertion, performance testing, transaction processing, and so on.
Decorator processing logic
When the interpreter reads a decorator like @, it will first parse the content after @, use the function or class in the next line of @ as the parameter of the function behind @, and then assign the return value to the modified function object in the next line
Rules for creating function modifiers
(1) The modifier is a function
(2) The modifier takes the modified function as a parameter
(3) The modifier returns a new function
(4) The modifier maintains the signature of the maintained function
for example
Example 1: The modified function does not take parameters
def log(func):
def wrapper():
print('log开始 ...')
func()
print('log结束 ...')
return wrapper
@log
def test():
print('test ..')
test()
operation result:
log开始 ...
test ..
log结束 ...
Example 2: The modified function takes parameters
from functools import wraps
def log(func):
@wraps(func)
def wrapper(*args,**kwargs):
print('log开始 ...',func.__name__)
ret = func(*args,**kwargs)
print('log结束 ...')
return ret
return wrapper
@log
def test1(s):
print('test1 ..', s)
return s
@log
def test2(s1, s2):
print('test2 ..', s1, s2)
return s1 + s2
test1('a')
test2('a','bc')
operation result:
log开始 ... test1
test1 .. a
log结束 ...
log开始 ... test2
test2 .. a bc
log结束 ...
Example 3: Modifiers have parameters and need to be wrapped in more than the above example
from functools import wraps
def log(arg):
def _log(func):
@wraps(func)
def wrapper(*args,**kwargs):
print('log开始 ...',func.__name__, arg)
ret = func(*args,**kwargs)
print('log结束 ...')
return ret
return wrapper
return _log
@log('module1')
def test1(s):
print('test1 ..', s)
return s
@log('module1')
def test2(s1, s2):
print('test2 ..', s1, s2)
return s1 + s2
test1('a')
test2('a','bc')
operation result:
log开始 ... test1 module1
test1 .. a
log结束 ...
log开始 ... test2 module1
test2 .. a bc
log结束 ...