python装饰器

2018-07-12  本文已影响0人  奔跑的老少年

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

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返回。

上一篇 下一篇

猜你喜欢

热点阅读