python装饰器

高阶函数:参数或返回值是函数的函数。
装饰器:通俗来说就是高阶函数+嵌套函数,在工作中我们不能修改线上别人写的代码,假如我们现在需求模块需要用到线上的某个函数,且需要为其增加一些新功能,我们既不能修改原函数内容,也不能修改器调用方式,那么使用装饰器就能解决此问题。

def timer(func):
    def deco():
        func()
        print('deco contains func')
    return deco

@timer
def test1():
    print('this is test1')

test1()

假设已存在test1函数,我们想要给test1打印一条内容'deco contains func',在不改变原test1函数代码、test1调用方式的情况下,我们可以定义一个timer装饰器,timer函数里包含另一个函数deco,且返回deco函数。在deco函数中调用func函数(func是函数,func()是其返回值)并加上新增的功能,最后返回deco函数。在被装饰的函数前面加上‘@装饰函数名’,直接调用test1就执行了新增的功能。执行结果如下:

this is test1
deco contains func

@timer相当于test1 = timer(test1),timer(test1)返回的是一个函数,想要知道期结果还需调用一下test1()

def timer(func):
    def deco():
        func()
        print('deco contains func')
    return deco

# @timer
def test1():
    print('this is test1')

test1 = timer(test1)
test1()

执行结果:

this is test1
deco contains func

当被装饰的函数需要带有参数时,可在deco函数内传入参数:

def timer(func):
    def deco(*args,**kwargs):
        func(*args,**kwargs)
        print('deco contains func')
    return deco

@timer
def test1():
    print('this is test1')

@timer
def test2(*args,**kwargs):
    print('info of %s is %s'% (args[0],kwargs))

test1()
test2('Tim',age = 22,city = 'beijing')

打印结果:

this is test1
deco contains func
info of Tim is {'city': 'beijing', 'age': 22}
deco contains func

args为可变参数,结果包装成一个tulpe返回,*kwargs未关键字参数,结果包装成dic返回。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转载来自:http://blog.csdn.net/u013471155 在学习Python的过程中,我相信有很多...
    JM68阅读 3,688评论 3 9
  • 说到装饰器,很明显就是用来装饰的,既然是要装饰,那肯定是在保留原有的基础上再添加一些东西作为装饰,这就是我对装饰器...
    张氏小毛驴阅读 1,722评论 0 0
  • 每个人都有的内裤主要功能是用来遮羞,但是到了冬天它没法为我们防风御寒,咋办?我们想到的一个办法就是把内裤改造一下,...
    chen_000阅读 5,150评论 0 3
  • 体重还行,身高也不算矮,年龄36,职业是大学老师,工资的话勉强吧。喜欢的人可能是不喜欢自己,然后可能也没有人喜欢自...
    大胖鲸鱼阅读 3,114评论 0 0
  • 我一直觉得我是个“不合群”的人。 以前遇上有人约吃饭喝茶,我第一反应就是想办法推拖拒绝。 我不喜欢去太热闹的场合,...
    一言这阳光正好阅读 4,429评论 0 5