Home >Backend Development >Python Tutorial >Python basics decorators and exercises

Python basics decorators and exercises

coldplay.xixi
coldplay.xixiforward
2020-12-22 17:45:002684browse

Python video tutorialExplaining decorators

Python basics decorators and exercises

##Recommended free:

Python video tutorial

Decorator concept

Decorator, to put it bluntly, is a

function## 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.

What does the decorator look like?

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()

@wrapper

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@wrapper
Quickly 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

== 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>

As shown in the figure below

Python basics decorators and exercises##It can be seen from this

## In #function

inner, 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!

Statement:
This article is reproduced at:jianshu.com. If there is any infringement, please contact admin@php.cn delete