Python 函数修饰符(装饰器)的学习

来源:互联网 发布:java聊天室项目 编辑:程序博客网 时间:2024/06/05 07:34

#Python 函数修饰符(装饰器)的学习

import timeclass Test:    def __init__(self):        self.name=''        self.functionDict = {}    def msg_register(self, msgType,            isFriendChat=False, isGroupChat=False, isMpChat=False):        def _msg_register(fn):            print 'call fn'            self.functionDict[msgType] = fn        return _msg_register    def do(self,msgType):        self.functionDict[msgType]('abc',self.name)    def timeslong(self,func):        def call():            start = time.clock()            print("It's time starting ! ")            func()            print("It's time ending ! ")            end = time.clock()            return "It's used : %s ." % (end - start)        return calla =  Test()a.name='111'@a.msg_register('First')def test(msg,tt):    print 'msg=',msg    print tta.do('First')a.name='222'def testImg(msg,tt):    print 'msg=',msg    print tta.functionDict['Second'] = testImga.do('Second')@a.timeslongdef f():    y = 0    for i in range(10):        y = y + i + 1        print(y)    return yprint(f())

运行结果:

call fnmsg= abc111msg= abc222It's time starting ! 13610152128364555It's time ending ! It's used : 0.0278254513276 .