python装饰器讲解
发布日期:2021-05-14 15:03:32 浏览次数:19 分类:精选文章

本文共 1856 字,大约阅读时间需要 6 分钟。

Python 装饰器讲解

装饰器的基本概念

装饰器是一种在不改变原函数功能的前提下,向函数中注入额外功能或改变其行为的技术。通过使用装饰器,可以在代码中添加新的功能,简化代码管理流程。

以计算函数运行时间为例

在实际编程中,装饰器的应用场景非常多。以下是一个典型的例子:计算函数运行时间。

第一次尝试

import timedef index():    time.sleep(2)start_time = time.time()index()end_time = time.time()print(end_time - start_time)

这个代码直接使用time.time()time.sleep()来计算函数运行时间,但实现简单,难以扩展。

第二次优化

import timedef index():    time.sleep(2)def calculate_time(f):    start_time = time.time()    f()    end_time = time.time()    print(end_time - start_time)calculate_time(index)

这个版本通过将index函数传递给calculate_time函数,实现了时间计算的功能,但仍然不够灵活。

第三次优化

import timedef index():    time.sleep(2)def calculate_time(f):    start_time = time.time()    f()    end_time = time.time()    print(end_time - start_time)calculate_time(index)

这个版本引入了函数inner,使得装饰器能够更灵活地处理函数调用。

第四次优化

import timedef index():    time.sleep(2)def calculate_time(f):    def inner():        start_time = time.time()        f()        end_time = time.time()        print(end_time - start_time)    return innerindex = calculate_time(index)

这个版本将calculate_time转换成了一个装饰器,通过@calculate_time语法糖实现,更方便阅读。

第五次优化

import timedef calculate_time(f):    def inner(*args, **kwargs):        start_time = time.time()        ret = f(*args, **kwargs)        end_time = time.time()        print(end_time - start_time)        return ret    return inner@calculate_timedef add(x, y):    time.sleep(2)    return x + yprint(add(3, 3))

这个版本支持函数的传参,更加灵活实用。

真正的装饰器(加上传递参数)

import timedef calculate_time(f):    def inner(*args, **kwargs):        start_time = time.time()        ret = f(*args, **kwargs)        end_time = time.time()        print(end_time - start_time)        return ret    return inner@calculate_timedef add(x, y):    time.sleep(2)    return x + yprint(add(3, 3))

这个实现支持任意函数参数,展示了装饰器的实际应用场景。

总结

通过以上例子可以看出,装饰器是一种强大的功能扩展工具,能够在不改变原函数的前提下,灵活地添加功能。通过将函数传递给装饰器,可以实现对代码行为的丰富扩展,简化代码管理,提高代码复用性。

上一篇:pip使用国内镜像源(附加全局修改)
下一篇:linux下配置Anaconda路径

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年05月08日 22时45分39秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章