Example

#!/usr/bin/env python

import functools

def log_v1(arg):
    if callable(arg):
        func = arg
        @functools.wraps(func)
        def wrapper(*args, **kw):
            print 'call %s()' % (func.__name__)
            print "begin call"
            func(*args, **kw)
            print "end   call"
        return wrapper
    else:
        def decorator(func):
            @functools.wraps(func)
            def wrapper(*args, **kw):
                print '%s %s()' % (arg, func.__name__)
                print "begin call"
                func(*args, **kw)
                print "end   call"
            return wrapper
        return decorator

def log_v2(arg):
    if isinstance(arg, str):
        def decorator(func):
            @functools.wraps(func)
            def wrapper(*args, **kw):
                print '%s %s()' % (arg, func.__name__)
                print "begin call"
                func(*args, **kw)
                print "end   call"
            return wrapper
        return decorator
    else:
        func = arg
        @functools.wraps(func)
        def wrapper(*args, **kw):
            print 'call %s()' % (func.__name__)
            print "begin call"
            func(*args, **kw)
            print "end   call"
        return wrapper

#@log_v2
@log_v1
def fa():
    print "---> fa()"

#@log_v2('execute')
@log_v1('execute')
def fb():
    print "---> fb()"

if __name__ == "__main__":
    fa()
    fb()

Output

call fa()
begin call
---> fa()
end   call
execute fb()
begin call
---> fb()
end   call

装饰器

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐