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 文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值