Python中的装饰器

来源:互联网 发布:五胡乱华 知乎 编辑:程序博客网 时间:2024/05/04 08:37

python中装饰器是一个很神奇的功能,可以给我们带来许多意想不到的简便。


装饰器本身是一个python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。它经常用于有切面需求的场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。

装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以剥离出大量与函数功能本身无关的雷同代码并继续重用。

概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能。

拆解讲解如下,注意区别:

1.

def myDecorator(function):    def statsticTime():        import time        start = time.clock()        print 'start at: ', start        function()        end = time.clock()        print 'end at: ', end    return statsticTime

此时使用:

@myDecoratordef a():    print 'i love China'    return 'i love Python'

运行:

a()
输出为:

start at:  1828.02588511i love Chinaend at:  1828.02606038
2.

def myDecorator(function):    def statsticTime():        import time        start = time.clock()        print 'start at: ', start        function()        end = time.clock()        print 'end at: ', end    return statsticTime()

@myDecoratordef a():    print 'i love China'    return 'i love Python'

此时直接会有输出:

start at:  2110.53246682i love Chinaend at:  2110.53259472


3.

def myDecorator(function):    def statsticTime():        import time        start = time.clock()        print 'start at: ', start        function        end = time.clock()        print 'end at: ', end    return statsticTime@myDecoratordef a():    print 'i love China'    return 'i love Python'a()
输出:

start at:  2288.03029055end at:  2288.03034266

4.

def myDecorator(function):    def statsticTime(*args,**kwargs):        import time        start = time.clock()        print 'start: ', start        function(*args,**kwargs)        end = time.clock()        print 'end: ', end        print 'end - start: ', end - start        return function(*args, **kwargs)    return statsticTime
@myDecoratordef a():    print 'i am the world'    return 'i love u'

运行:

a()

输出:

start:  2382.26522127i am the worldend:  2382.26529666end - start:  7.53977528802e-05i am the worldout:'i love u'





0 0
原创粉丝点击