Decorator- Decorator in Python

The content of this blog is only some understanding and summary of the blogger himself, if there is any error, please correct me~

The function of the decorator is to add other functions before and after the original function without modifying the calling method of the original function

The decorator is a closure function, which is equivalent to a kind of nesting of functions. The decorator is open for extension and closed for modification

Here are some practical examples to understand the decorator

First look at the role of a single decorator :

def w1(func):
    print('----w1----')
    def inner():
        print('----before----')
        func()
        print('----after----')
    return inner

@w1
def f1():
    print('----f1----')
    
# 输出:----w1----

f1()
# 输出:----before----
#      ----f1----
#      ----after----

It can be seen that the entire calling process is equivalent to embedding f1() into w1(), replacing func() in w1() with w1(), and then executing w1()

Look at the next example, you can further understand the execution process outside and inside the function

def func(functionName):
    print("----func----1----")
    def func_in():
        print("----func_in----1----")
        functionName()
        print("----func_in----2----")

    print("----func----2----")
    return func_in

@func
def test():
    print("----test----")

#test = func(test)

test()

# 运行结果
# ----func----1----
# ----func----2----
# ----func_in----1----
# ----test----
# ----func_in----2----

It can be found that the operation outside the built-in function is executed first, and then the inner function is executed, and the execution of the outer function does not require the call of the function. As can be seen from the above example, print(----w1----) Before executing f1()

Then look at the execution of multiple decorators :

def a(func):
    print('i\'m a!')
    def e():
        print(1)
        func()
        print(2)
    return e
def b(func):
    print('i\'m b!')
    def d():
        print('a')
        func()
        print('b')
    return d
@b
@a
def c():
    print('!!!!!')
c()
# output:
# i'm a!
# i'm b!
# a
# 1
# !!!!!
# 2
# b

If you don’t use decorators, you can simplify as follows

# 这里的func()表示的是e()
def b():
    print('a')
    func()
    print('b')
   

# 这里的func()表示的是c()
def b():
    print('a')
    print(1)
    func()
    print(2)
    print('b')

def b():
    print('a')
    print(1)
    print('!!!!!')
    print(2)
    print('b')    

It can be seen that it is equivalent to nesting c() to a() first, and then nesting a() to b() to achieve one level of nesting.

Guess you like

Origin blog.csdn.net/qq_24852439/article/details/104855147