Detailed Explanation and Application Example of python Decorator
- 2021-12-12 05:17:08
- OfStack
What is a decorator
Literally, a decorator is a tool used to decorate something else. In python, decorators are divided into function decorators and class decorators.
In short, function decorators are decorators used to decorate functions, and their main purpose is to increase the functions of objective functions. Class decorators are decorators that decorate classes and increase the functions of classes.
Function decorator
Decorators are essentially nested functions
Here is a simple decorator
# fun1 Is the decorator name, function Refers to the decorated function
def fun1(function):
def fun2():
print(" Here we go! ")
function() # Execute the decorated function or Or return function()
return fun2
Outside
fun1()
You need to pass in 1 parameter, which is used to pass in the function to be decorated.
fun2()
Need to execute
function
This parameter.
This is passing a function as an argument to another function.
Usage:
Add @ decorator name to the function to be decorated
@fun1
def fun3():
print("aaa")
fun3()
It can be equivalent to this:
def fun3():
print("aaa")
fun = fun1(fun3)
fun()
The output result is 1
Implementation results:
Here we go!
aaa
If the passed-in function requires parameters, you can write this:
def fun1(function):
def fun2(a):
print(" Here we go! ")
function(a)
return fun2
@fun1
def fun3(a):
print(a)
fun3("aaa")
Output:
Here we go!
aaa
If it is not clear how many arguments the passed-in function requires, you can write this:
def fun1(function):
def fun2(*args, **kwargs):
print(" Here we go! ")
function(*args, **kwargs)
return fun2
@fun1
def fun3(a,b):
print(a,b)
@fun1
def fun4(a,b,c):
print(a,b,c)
fun3("aaa","bbb")
fun4("ccc","ddd","eee")
Run results:
Here we go!
aaa bbb
Here we go!
ccc ddd eee
If the function decorator needs to add parameters, you can write this:
def fun(msg):
def fun1(function):
def fun2(*args, **kwargs):
print(" Here we go! {}".format(msg))
function(*args, **kwargs)
return fun2
return fun1
@fun(msg=" Children ")
def fun3(a,b):
print(a,b)
fun3("aaa","bbb")
Run results:
Here we go! Children
aaa bbb
Class decorator
The usage of class decorator is basically like function decorator 1, but it is a decorator written with class
class fun1(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print((" Here we go! ")
self.func(*args, **kwargs)
@fun1
def fun2(a,b):
print(a,b)
fun2("aaa","bbb")
Class decoration uses the class's
__call__
Method
Run results:
Here we go!
aaa bbb
You can also write this:
class fun(object):
def __init__(self, msg):
self.msg = msg
def __call__(self, func):
def fun1(*args, **kwargs):
print(" Here we go! {0}".format(self.msg))
func(*args, **kwargs)
return fun1
@fun(msg=" Children ")
def fun2(a, b):
print(a, b)
fun2("aaa,","bbb")
Run results:
Here we go! Children
aaa, bbb