Python 装饰器简单介绍

def log(func):
    def wrapper(*args, **kw):
        print '===call %s():' %func.__name__
        return func(*args, **kw)
    return wrapper

def logWithParam(text):
    def decorator(func):
        def wrapper(*args, **kw):
            print '%s ===call %s():' % (text, func.__name__)
            return func(*args, **kw)
        return wrapper
    return decorator

def logWithParamOrNot(text = 'test'):
    def decorator(func):
        def wrapper(*args, **kw):
            print '%s ===call %s():' % (text, func.__name__)
            return func(*args, **kw)
        return wrapper
    return decorator

def logWithPrint(func):
    def wrapper(*args, **kw):
        print 'begin call %s():' % func.__name__
        func(*args, **kw)
        print 'end call %s():' % func.__name__
        # do not need return
    return wrapper

# @log                  # now = log(now)
# @logWithParam('test')  # now = logWithParam('test')(now)
# @logWithParamOrNot()  # now = logWithParamOrNot(now)
@logWithPrint           # now = logWithPrint(now)
def now():
    print '2016-5-17'


if __name__ == '__main__':
    now()

参考资料:

  http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386819879946007bbf6ad052463ab18034f0254bf355000#0

posted @ 2016-05-17 11:14  skyko  阅读(363)  评论(0编辑  收藏  举报