您的位置:首页 > 编程语言 > Python开发

Python基础:13装饰器

2015-06-02 16:49 681 查看
装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的应用有插入日志、性能测试、事务处理等。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数功能本身无关的雷同代码并继续重用。概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能。

1:装饰器实际就是函数。他们接受函数对象。对这些函数进行包装或修饰。因此,有了装饰器,可以在执行实际函数之前运行预备代码;也可以在执行实际函数代码之后做些清理工作。

2:装饰器的语法以@开头,接着是装饰器函数的名字和可选的参数。紧跟着定义被修饰的函数,所以,使用装饰器看起来会是这样:
@decorator(dec_opt_args)
def func2Bdecorated(func_opt_args):
    ...


3:装饰器的本质
在装饰器没有参数的情况下,如:
@deco
def foo():     pass

该定义等价于:
foo = deco(foo)


在装饰器有参数的情况下,如:
@deco(deco_args)
def foo():     pass

该定义等价于:
foo = deco(deco_args)(foo)


更复杂的,装饰器也可以“堆叠”,如:
@deco1(deco1_args)
@deco2
def foo():     pass

该定义等价于:
foo = deco1(deco1_args)(deco2(foo))


下面是不带参数的装饰器例子:
def  deco(func):
       print 'this is deco'
       def wrapfun():
              print 'in  wrapfun'
              return func()
       return wrapfun

@deco
def  foo():
       print 'this is foo'
 
print  'after def'
 
foo()


结果是:
this is deco
after def
in wrapfun
this is foo


可见,在定义foo函数的时候,就会调用deco函数。下面是带参数的装饰器例子:
def deco(args):
       print  'this is deco, args is ', args
       def  wrapfun1(func):
              print  'in wrapfun1'
              def  wrapfun2(fargs):
                     print  'in wrapfun2'
                     return  func(fargs)
              return  wrapfun2
       return  wrapfun1
 
@deco([1,2,3])
def foo(fargs):
       print  'this is foo, fargs is ', fargs
 
print 'after def'
 
foo([4, 5, 6])


结果是:
this is deco, args is [1, 2, 3]
in wrapfun1
after def
in wrapfun2
this is foo, fargs is  [4, 5, 6]


装饰器其实用到了闭包。只有理解了装饰器的本质,才能写出没有错误的装饰器。可以在python langugae reference, python2.4 中“What’s New in Python 2.4”的文档以及PEP 318 中来阅读更多关于装饰器的内容。


参考
http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: