The decorator is essentially a python Function or class , It allows other functions or classes to add additional functionality without any code changes , The return value of the decorator is also a function / Class object .
Use scenarios : Inserting log 、 Performance testing 、 Transaction processing 、 cache 、 Permission check and other scenarios
advantage : We have decorators , We can extract a large number of similar code independent of the function itself into the decorator and continue to reuse , General speaking , The role of decorators is to add additional functionality to existing objects in time .
def log(func):
def wrapper(*args,**kwargs):
print("{} Log ".formate(func.__name__))
return func(*args,**kwargs)
return wrapper
@log
def test_func():
pass
python A function in can be passed to another function like a parameter .
def func1():
print("func1 Be performed ~")
def func2(func):
func()
func2(func1) # func1 Be performed ~
import logging
logging.warning(logging message)
import logging
def func1():
print("func1 Be performed ~")
logging.warning("func1 Operation log of ~")
def func2(func):
func()
func2(func1)
def func1():
print("func1 Be performed ~")
def func2():
print("func2 Be performed ~")
def func3():
print("func3 Be performed ~")
def func_log(func):
logging.warning('''{} Running ~~'''.format(func.__name__))
func()
func_log(func1)
func_log(func2)
func_log(func3)
Through the above example, we find that , To achieve the function of executing functions and printing logs , We need to call the log function to achieve our goal , It is difficult to execute functions and print logs simply by function names , At this point, the benefits of the decorator are reflected …
# Call of decorator
def func_logging(func):
def wrapper():
print("{} Log ".format(func.__name__))
func()
return wrapper
@func_logging
def func1():
print("func1 Function executed ")
func1()
# Decorator calling principle
def func_logging(func): # func--->func1
def wrapper():
print("{} Log ".format(func.__name__))
func()
return wrapper # function
def func1():
print("func1 Function executed ")
func1 = func_logging(func1)
func1()
# The decorated function has arguments ( Some with parameters , Some have no parameters , The number of some parameters is uncertain )
def func_logging(func):
def wrapper(*args, **kwargs):
print("{} Log ".format(func.__name__))
func(*args, **kwargs)
return wrapper
@func_logging
def func1(name):
print("func1 Function executed ",name)
@func_logging
def func2(name, age):
print("func2 Function executed ",name, age)
@func_logging
def func3():
print("func3 Function executed ")
func1('func1')
func2("func2",18)
func3()
It was written before :Python
source : impression pythonrepo