Python编程学习——装饰器

简介:
装饰器,Python2.4版本引入的一种新特性。跟名字一样,是用来装饰的。其实装饰器就是一个函数,不过形式比较特殊,一般用”@”开头,一般形式如下:

@deco
def foo(): pass

上面的代码等同于下面这句代码:

foo = deco(foo)

装饰器既可以和上面一样没有参数,也可以是带参数的:

@decomaker(deco_args)
def foo(): pass

等价于:

foo = decomaker(deco_args)(foo)

代码举例:

from time import ctime, sleep
def log(func):
    def wrappedFunc():
        print '[%s] %s() called' % (ctime(), func.__name__)
        return func()
    return wrappedFunc
@log
def foo():
    pass
for i in xrange(5):
    sleep(1); foo()

运行结果:

[Mon Sep 21 21:43:12 2015] foo() called
[Mon Sep 21 21:43:13 2015] foo() called
[Mon Sep 21 21:43:14 2015] foo() called
[Mon Sep 21 21:43:15 2015] foo() called
[Mon Sep 21 21:43:16 2015] foo() called

代码中使用内嵌包装函数,保证每次调用函数装饰器都会工作。在使用装饰器的时候注意返回值,需要与原函数一致。

带参数的装饰器:

from time import ctime, sleep
def log(arg):
    print "I'm function %s" % arg
    def deco(func):
        def wrappedFunc():
            print '[%s] %s() called' % (ctime(), func.__name__)
            return func()
        return wrappedFunc
    return deco
@log
def foo():
    pass
for i in xrange(5):
    sleep(1); foo()

运行结果:

I'm function foo
[Mon Sep 21 22:28:19 2015] foo() called
[Mon Sep 21 22:28:20 2015] foo() called
[Mon Sep 21 22:28:21 2015] foo() called
[Mon Sep 21 22:28:22 2015] foo() called
[Mon Sep 21 22:28:23 2015] foo() called

参考资料:
装饰器—廖雪峰的官方网站
Python核心编程(第二版)
What’s New in Python 2.4 文档

你可能感兴趣的:(Python编程学习——装饰器)