装饰器

2018-09-05  本文已影响0人  大地瓜_

1、装饰器引入

Python装饰器就是用于拓展原来函数功能的一种函数,这个函数的特殊之处在于它的返回值也是一个函数,使用python装饰器的好处就是在不用更改原函数的代码前提下给函数增加新的功能。

在不修改原函数的功能基础上,如果我们想要扩展函数功能(例如统计函数的运行时间)

import time

def func():
    print "hello",
    print "world"

def deco(func):
    startTime = time.time()
    func()
    endTime = time.time()
    print "the time is", (endTime - startTime )

deco(func)

上面代码中,将func作为参数传入函数,其实是一个Python函数内嵌的实现。

如果要调用很多个类似的函数,例如func1、func2....等函数代码会特别复制,因此引入装饰器。

2、装饰器

下面引入一个基本的装饰器

import time


def deco(func):
    def wrapper():
        startTime = time.time()
        func()
        endTime = time.time()
        print "the time is", (endTime - startTime)
    return wrapper


@deco
def func():
    print "hello",
    print "world"

func()

装饰器的基本结构
定义一个内嵌函数wrapper(),然后返回值为内嵌函数,内嵌函数的内部调用函数。python装饰器本质上就是一个函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外的功能,装饰器的返回值也是一个函数对象(函数的指针)

其实函数本质执行的函数为deco(func)

3、带参数的装饰器

如果对于含有参数的装饰器应该怎么处理,即如果在上文中的func(a, b)
我们引入通用装饰效果func(*args, **kwargs),对于任何参数据可以满足,即现在的装饰器代码可以重构为

import time
def deco(func):
   def wrapper(*args, **kwargs):
       startTime = time.time()
       func(*args, **kwargs)
       endTime = time.time()
       print "the time is", (endTime - startTime)
   return wrapper

@deco
def func2(a, b):
   print "hello",
   print "world",
   print a+b

@deco
def func3(a, b,c):
   print "hello",
   print "world",
   print a+b+c

func2(1,2)
func3(1,2,3)

通过在内嵌函数中引入参数,然后传递给调用函数,这样就可以将实现多参数的修饰器,注意记住参数func(*args, **kwargs)

4、多装饰器函数

多个装饰器执行的顺序就是从最后一个装饰器开始,执行到第一个装饰器,再执行函数本身

def dec1(func):
    print("1111")
    def one():
        print("2222")
        func()
        print("3333")
    return one

def dec2(func):
    print("aaaa")
    def two():
        print("bbbb")
        func()
        print("cccc")
    return two

@dec1
@dec2
def test():
    print("test test")

test()

输出结果

aaaa
1111
2222
bbbb
test test
cccc
3333
def wa1(test):
    def wapper():
        print "<b>"
        test()
        print "</b>"
    return wapper

def wa2(test):
    def wapper():
        print "<i>"
        test()
        print "</i>"
    return wapper

@wa1
@wa2
def test():
    print("test")

test()
<b>
<i>
test
</i>
</b>

上面修饰器由远及近进行计算

上一篇 下一篇

猜你喜欢

热点阅读