python中的修饰器

python中的修饰器@…
浅谈python修饰器

  • 修饰器就是为已经存在的对象,添加一些其他的功能
    较为经典的有插入日志,性能检测,如运行该函数所耗费的时间,事件处理等
  • 利用修饰器方便代码重用
  • 被修饰函数做为修饰函数的参数!!!
    exampleOne
def make_bold(fn):
    def wrapped():
        return "<b>"+fn()+"<b>"
    return wrapped

def make_i(fn):
    def wrapped():
        return "<i>"+fn()+"<i>"
    return wrapped

'''注意这两个修饰(包装)器的使用顺序'''
@make_bold   # 相当于是make_bold(hello())
@make_i  # 相当于是make_i(hello())
def hello():
    return "hello"

print(hello())       
# result: <b><i>hello<i><b>

exampleTwo:统计函数运行所耗时间

import time
def time_it(func):
    def wrapper():
        start=time.clock()
        func()
        end=time.clock()
        print( 'the cost time of this function is', end-start)
    return wrapper

@time_it
def f1():
    print("this is a function")  
# result:this is a function ,the cost time of this function is 1.6e-05
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值