首页 > 其他 > 详细

一个用户统计函数调用事件的装饰器

时间:2014-12-30 22:01:07      阅读:266      评论:0      收藏:0      [点我收藏+]

装饰器前面提过了,采用python的闭包特性实现:

from time import time
from time import sleep

def count_time():
    def tmp(func):
        def wrapped(*args, **kargs):
            begin_time = time()
            result = func(*args, **kargs)
            end_time = time()
            cost_time = end_time - begin_time
            print %s called cost time : %s %(func.__name__, cost_time)
            return result
        return wrapped
    return tmp

@count_time()
def test():
    sleep(0.5)

if __name__ == __main__:
    test()

我们尝试以下的代码:

class Test:
    @count_time()
    def test(self):
        print haha

if __name__ == __main__:
#    test()
    a = Test()
    a.test()

代码仍然可以正常工作,因为a.test()仅仅就是给test添加了一个额外的参数a而已。

 

有些情况下,我们希望某个装饰器只用来修饰class中的方法,此时我们就需要给闭包中的函数添加一个参数self:

from time import time
from time import sleep

def count_time():
    def tmp(func):
        def wrapped(self, *args, **kargs):
            begin_time = time()
            result = func(self, *args, **kargs)
            end_time = time()
            cost_time = end_time - begin_time
            print %s called cost time : %s %(func.__name__, cost_time)
            return result
        return wrapped
    return tmp

此时我们使用普通函数测试,结果报错:

Traceback (most recent call last):
  File "9.py", line 17, in <module>
    @count_time
TypeError: count_time() takes no arguments (1 given)
证明我们的装饰器只能用于修饰class内的成员函数。

一个用户统计函数调用事件的装饰器

原文:http://www.cnblogs.com/inevermore/p/4194584.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!