Python--Decorator and its application (a function that expands the function of the original function)

1. Decorator

1.1 The concept of decorators

python装饰器(Fuctional Decorators)是用于拓展原来函数功能的一种函数,
目的是在不改变原函数名(或类名)的情况下,给函数增加新的功能。
通常情况下,装饰器主要运用在引入日志,函数执行时间统计,
执行函数前预备处理,执行函数后清理功能,权限校验以及缓存方面。

1.1.1 Statistics function execution time without decorator

import time


# 函数运行3s
def func():
    time.sleep(3)


start_time = time.time()
func()
end_time = time.time()
print("函数的运行时间是: %.2f 秒" % (end_time - start_time))

operation result:
Insert picture description here


1.1.2 Statistic function execution time with decorator

上述代码只执行了一次,原则上是没有问题的,如果有多个这样的需求,就会大量
重复代码。为了减少代码的重复,可以创建一个新的函数专门记录函数的执行时间
。在Python中,装饰器可以做到这一点,其语法以@开头。
import time


# 装饰器
def timeit(func):  # func为装饰器绑定的方法(绑定装饰器后自动传入)
    def result():
        start_time = time.time()
        func()  # 调用test方法
        end_time = time.time()
        print('函数运行时间为:%.2fs' % (end_time - start_time))

    return result  # 返回result方法


@timeit  # 添加装饰器
def test():
    print("函数运行测试")
    time.sleep(2)


test()  # 调用函数

operation result:
Insert picture description here

当程序执行到test()的时候,发现它上面还有@timeit,所以会先执行
@timeit。@timeit等价于test()=  timeit(test())。

1.2 Use of decorators

1.2.1 Application of decorator without parameters

import time


def timeit(func):
    def result():
        start_time = time.time()
        func()
        end_time = time.time()
        print("函数的运行时间是: %.2f 秒" % (end_time - start_time))

    return result


@timeit
def func_1():
    time.sleep(1)


@timeit
def func_2():
    time.sleep(2)


# 调用函数
func_1()
func_2()

operation result:
Insert picture description here


1.2.2 Use of decorators with parameters

import time


def timeit(func):  # func为装饰器绑定的方法(绑定装饰器后自动传入)
    def result(arg1):  # 传入test方法的参数
        start_time = time.time()
        func(arg1)  # 调用test方法
        end_time = time.time()
        print('函数运行时间为:%.2fs' % (end_time - start_time))

    return result  # 返回result方法


@timeit  # 添加装饰器
def test(mStr):
    print(mStr)
    time.sleep(2)


test("测试函数运行时长:")  # 调用函数

Insert picture description here


1.2.3 Decorator can decorate functions with or without parameters

import time


# 装饰器
def timeit(func):  # func为装饰器绑定的方法(绑定装饰器后自动传入)
    def result(*arg1, **kwargs):  # (传入非固定参数)这样即使装饰函数不带参数也可被装饰
        start_time = time.time()
        func(*arg1, **kwargs)
        end_time = time.time()
        print('函数运行时间为:%.2fs' % (end_time - start_time) + "\n")

    return result  # 返回result方法


@timeit  # 添加装饰器
def test_01():
    time.sleep(2)


@timeit  # 添加装饰器
def test_02(msg):
    print(msg)
    time.sleep(2)


test_01()  # 调用函数 不带参数
test_02("测试函数运行时长:")  # 调用函数 带参数

operation result:
Insert picture description here



Guess you like

Origin blog.csdn.net/I_r_o_n_M_a_n/article/details/115343399