Python3 advanced---decorator

1. Decorator function:

   Enhance the function of the function without modifying the original function

2. Function without parameters + decorator without parameters

 (1) The decorated function of foo()

 (2) show_time() is a decorator

# -*- coding:utf-8 -*-
import time


def show_time(func):
    def inner():
        start_time = time.time()
        func()
        end_time = time.time()
        print("执行时间为:", end_time - start_time)

    return inner


@show_time
def foo():
    print("我是foo函数")
    time.sleep(1)


foo()

3. Function with parameters + decorator without parameters

# -*- coding:utf-8 -*-
import time


def show_time(func):
    def inner(*args, **kwargs):
        start_time = time.time()
        func(*args, **kwargs)
        end_time = time.time()
        print("执行时间为:", end_time - start_time)

    return inner


@show_time
def foo(something):
    print("我在:", something)
    time.sleep(1)


foo("看电视")

4. Function with parameters + decorator with parameters

# -*- coding:utf-8 -*-
# -*- coding:utf-8 -*-
import time


def wrapper(name):
    def show_time(func):
        def inner(*args, **kwargs):
            start_time = time.time()
            func(*args, **kwargs)
            end_time = time.time()
            print(name)
            print("执行时间为:", end_time - start_time)

        return inner

    return show_time


@wrapper("test")  # wrapper("test")(foo)("看电视")
def foo(something):
    print("我在:", something)
    time.sleep(1)


foo("看电视")

 

Additional explanation:

1. Function:

(1) The function name can be used as a parameter

(2) The function name can be used as the return value

(3) Function name can be assigned

2. Closure: The function inside the function refers to the variable of the nested scope, then this internal function is called a closure (inner function is a closure)

   

 

 

Guess you like

Origin blog.csdn.net/qq_19982677/article/details/108166933