Python中的装饰器

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


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

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

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

其实就是分别将要运行的函数,和要运行的函数的参数分别作为参数(有点绕),传递到另外两个函数中去,两外两个函数作为out包装函数和inner包装函数对要运行的函数进行修饰,

伪代码大概是这个样子的:

函数1(要装饰的函数):

函数2(要装饰的函数的参数):

要装饰的函数()=== 要调用的函数在此调用

返回函数2


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

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



此时使用:

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

运行:

a()
输出为:

start at:  1828.02588511
i love China
end 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()

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

此时直接会有输出:

start at:  2110.53246682
i love China
end 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

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

a()
输出:

start at:  2288.03029055
end 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
@myDecorator
def a():
    print 'i am the world'
    return 'i love u'

运行:

a()

输出:

start:  2382.26522127
i am the world
end:  2382.26529666
end - start:  7.53977528802e-05
i am the world

out:'i love u'





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值