您当前的位置: 首页 >  Python

龚建波

暂无认证

  • 3浏览

    0关注

    313博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Python学习笔记:闭包与装饰器

龚建波 发布时间:2019-08-06 21:38:10 ,浏览量:3

0.前言

本来只是想学习下Python的装饰器,结果发现这货原来和闭包有关系。不得不说闭包真是个好东西,只可惜C++不能用嵌套函数来实现闭包。(本文只是学习记录,更深入的可以看文末参考博客)

1.了解闭包

闭包是带有上下文的函数,可以保存函数的状态信息,比如嵌套函数可以保存外层函数的变量。一般情况下,如果一个函数结束,函数的内部所有东西都会释放掉,还给内存,局部变量都会消失。但是闭包是一种特殊情况,如果外函数在结束的时候发现有自己的临时变量将来会在内部函数中用到,就把这个临时变量绑定给了内部函数,然后自己再结束。

正因为闭包可以保存状态,而装饰器本质上就是为对象附加额外的属性(状态)。所以,借助闭包就能轻易地实现装饰器了。

2.了解装饰器

我百度搜Python装饰器,大多数都是先举个统计函数运行时间的例子,不过挺经典的,我还是把代码copy一下:

import time
from functools import wraps

def hello():
    print("say hello")
def run_time(func): 
    @wraps(func)
    def wrap():
        start_time=time.time()
        func()
        end_time=time.time()
        print(func.__name__," excution time:{0} ms\n".format((end_time-start_time)*1000))
    return wrap;
hello2=run_time(hello)
hello2()
#
# say hello
# hello excution time:0.99 ms

#使用@语法糖形式
@run_time
def cat():
    print("miao~~~")
cat()
#
# miao~~~
# cat excution time:0.5 ms

上面的例子我直接把"@wraps"也写出来了 ,他的作用就是把被装饰的函数(传入的函数)的一些属性赋值给装饰器函数(返回那个函数)。

带参数的装饰器(带参数的装饰器就是在原闭包的基础上又加了一层闭包):

def func_args(pre='xiaoqiang'):
    def w_test_log(func):
        def inner():
            print('...记录日志...visitor is %s' % pre)
            func()
        return inner
    return w_test_log
# 带有参数的装饰器能够起到在运行时,有不同的功能
# 先执行func_args('wangcai'),返回w_test_log函数的引用
# @w_test_log
# 使用@w_test_log对test_log进行装饰
@func_args('wangcai')
def test_log():
    print('this is test log')
test_log()
#
# ...记录日志...visitor is wangcai
# this is test log

通用装饰器(匹配任意的函数参数):

def w_test(func):
    def inner(*args, **kwargs):
        ret = func(*args, **kwargs)
        return ret
    return inner
@w_test
def test():
    print('test called')
@w_test
def test1():
    print('test1 called')
    return 'python'
@w_test
def test2(a):
    print('test2 called and value is %d ' % a)
test()
test1()
test2(9)
3.参考

参考博客(闭包与装饰器):https://blog.csdn.net/u013380694/article/details/90019571

参考博客(装饰器与wrap):https://www.cnblogs.com/slysky/p/9777424.html

 

关注
打赏
1655829268
查看更多评论
立即登录/注册

微信扫码登录

0.3123s