python 装饰器应用示例

# -*- coding: UTF-8 -*-


import time


#附加参数
def extend(func):
    
    def _extend(*args, **kwArgs):
        
        print func.__name__
        if 'owner' not in kwArgs:
            kwArgs['owner'] = 'captain'
        
        return func(*args, **kwArgs)
    return _extend


#验证参数
def valid(func):
    
    def _valid(*args,**kwArgs):
        
        print func.__name__
        if kwArgs['owner'] == 'captain':
            print 'extend captain params'
        else:
            print 'ok'
        
        return func(*args,**kwArgs)
    
    return _valid


#装饰器带参数
def timeit(msg = None,ok = False):
    
    def _timeit(func):
        
        def _deco(*args,**kwArgs):
            start = time.clock()
            ret = func(*args,**kwArgs)
            end =time.clock()
            print 'used:', round((end - start)*1000,5)
            return ret
            
        return _deco
    
    return _timeit




#类似于承包商转包,真正的函数执行是在最底层的承包商(timeit),上层的只是做了资质或附加了条款/条件
@extend
@valid
@timeit(u'耗时')
def foo(*args,**kwArgs):
    
    for k,v in kwArgs.items():
        print k,':',v


if __name__ == "__main__":
    
    foo(b = 'a11',a = 'b22',owner = 'hd')

你可能感兴趣的:(python)