Python装饰器,通过三个例子由浅入深讲透

1.主要功能与辅助功能写在一个函数。
2.通过辅助功能调用主要功能函数。
3.函数闭包:显式调用函数闭包。
最终:
使用装饰器,不需要显式调用函数闭包。

AI吧Python

第一版:
主要功能与辅助功能写在一个函数。

import time

def print_odds():
    """
    输出0~100之间所有奇数,并统计函数执行时间
    """
    start_time = time.clock()   # 起始时间
    # 查找并输出所有奇数
    for i in range(100):
        if i % 2 == 1:
            print(i)
    end_time = time.clock()     # 结束时间
    print("it takes {} s to find all the olds".format(end_time - start_time))

if __name__ == '__main__':
    print_odds()


第二版:
通过辅助功能调用主要功能函数。

import time

def count_time(func):
    """
    统计某个函数的运行时间
    """
    start_time = time.clock()  	# 起始时间
    func()  					# 执行函数
    end_time = time.clock()  	# 结束时间
    print("it takes {} s to find all the olds".format(end_time - start_time))

def print_odds():
    """
    输出0~100之间所有奇数,并统计函数执行时间
    """
    for i in range(100):
        if i % 2 == 1:
            print(i)

if __name__ == '__main__':
    count_time(print_odds)


第三版:
函数闭包:显式调用函数闭包。

import time

def print_odds():
    """
    输出0~100之间所有奇数,并统计函数执行时间
    """
    for i in range(100):
        if i % 2 == 1:
            print(i)

def count_time_wrapper(func):
    """
    闭包,用于增强函数func: 给函数func增加统计时间的功能
    """

    def improved_func():
        start_time = time.clock()   # 起始时间
        func()                      # 执行函数
        end_time = time.clock()     # 结束时间
        print("it takes {} s to find all the olds".format(end_time - start_time))

    return improved_func


if __name__ == '__main__':
    # 调用count_time_wrapper增强函数
    print_odds = count_time_wrapper(print_odds)
    print_odds()


最终版:
使用装饰器,不需要显式调用函数闭包。

import time

def count_time_wrapper(func):
    """
    闭包,用于增强函数func: 给函数func增加统计时间的功能
    """

    def improved_func():
        start_time = time.clock() 	# 起始时间
        func()  					# 执行函数
        end_time = time.clock()  	# 结束时间
        print("it takes {} s to find all the olds".format(end_time - start_time))

    return improved_func


@count_time_wrapper
def print_odds():
    """
    输出0~100之间所有奇数,并统计函数执行时间
    """
    for i in range(100):
        if i % 2 == 1:
            print(i)


if __name__ == '__main__':
    # 装饰器等价于在第一次调用函数时执行以下语句:
    # print_odds = count_time_wrapper(print_odds)
    print_odds()

结论:
Python装饰器本质上是对函数闭包的语法糖

https://blog.csdn.net/m0_56696177/article/details/119956342

发表评论

邮箱地址不会被公开。 必填项已用*标注