Home > Article > Backend Development > Python basics decorators and exercises
Python video tutorialExplaining decorators
##Recommended free:Decorator concept
Decorator, to put it bluntly, is afunction## used to decorate functions. #. The decorator follows the open-closed principle
and dependency inversion principle
. These two principles and concepts can be found on Baidu.
def wrapper(f):
def inner(*args,**kwargs):
ret = f(*args,**kwargs)
return ret
return inner
The above code is the fixed format of the decorator
Calling the decorator@wrapper # 简称语法糖
def test():
print(1)
test()
is calling the decorator, Compared with wrapper(test())
, it saves code and is more beautiful. Maybe you don’t understand when you see this, why do you need @wrapper
? The calling function is not wrapper()
? Actually, if you ask me to tell you, I don’t know. I just know that it is easier to write this way. Directly in front of the function to be decorated
@wrapperQuickly understand the decorator with a small example
def wrapper(f):
print(2)
def inner(*args,**kwargs):
print(3)
ret = f(*args,**kwargs)
print(4)
return ret
return inner
@wrapper
def test():
print(1)
test()
== wrapper(test())
It is equivalent to calling the decorator function. It will be easier to directly use the syntax sugar @wrapper
*args
is the matching For positional parameters, **kwargs
matches parameters passed by keyword, so that all parameters can be received. wrapper(test)
Receives the value and passes it to f
. In the inner circle function, ret = f(*args,**kwargs)
This function is Code that executes the decorated function. Then return the executed value, and finally return this function. The execution result of this code is: <pre class="brush:php;toolbar:false">2
3
1
4</pre>
##It can be seen from this
## In #functioninner, print(3)
is the operation before executing the decoration function, and print(4)
is the operation after executing the decoration function. It may be difficult to understand. So it’s best to give it a try.
Basic exercises
'''1. 默写装饰器固定格式 2. 写一个加减功能的装饰器 '''
The above is the detailed content of Python basics decorators and exercises. For more information, please follow other related articles on the PHP Chinese website!