python装饰器

        python装饰器就是用于拓展原来函数功能的一种函数,这个函数的特殊之处在于它的返回值也是一个函数,使用python装饰器的好处就是在不用更改原函数的代码前提下给函数增加新的功能。装饰器传入的参数就是一个函数,然后通过实现各种功能来对这个函数的功能进行增强。装饰器最大的优势是用于解决重复性的操作。

如下是一段简单的装饰器的例子,功能为给函数计时。只需在需要添加功能的函数上方@装饰器函数即可。

import time

def dec(fun):
    def wrapper():
        start = time.time()
        fun()
        end = time.time()
        msecs = (end - start)*1000
        print("time is %d ms" % msecs)
    return wrapper


@dec
def fun():
    print("hello")
    time.sleep(1)
    print("world")

if __name__ == '__main__':
    fun()
    #   hello
    #   world
    #   time is 1014 ms

        此外,一个函数可以有多个装饰器装饰。如下。

import time

def deco1(func):
    def wrapper(*args, **kwargs):
        print("this is deco01")
        func(*args, **kwargs)
        print("deco01 end here")
    return wrapper

def deco2(func):
    def wrapper(*args, **kwargs):
        print("this is deco02")
        func(*args, **kwargs)
        print("deco02 end here")
    return wrapper

@deco1
@deco2
def func(a,b):
    time.sleep(1)
    print("result is %d" %(a+b))



if __name__ == '__main__':
    f = func
    f(3,4)

    # this is deco01
    # this is deco02
    # result is 7
    # deco02 end here
    # deco01 end here

其中,可变参数*args和关键字参数**kwargs可使装饰器可以装饰任何数量参数的函数。

python中内置了如下几个装饰器:

@property:经过@property装饰过的函数返回的不再是一个函数,而是一个property对象。@staticmethod返回的是一个staticmethod类对象,而@classmethod返回的是一个classmethod类对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值