Discuss / Python / 定义有无参数调用的log装饰器

定义有无参数调用的log装饰器

Topic source

Tera worry

#1 Created at ... [Delete] [Delete and Lock User]
"""    日志装饰器"""import functoolsdef log(arg=None):    if callable(arg):        functools.wraps(arg)        def wrapper(*args, **kw):            print("begin call")            result = arg(*args, **kw)            print("end call")            return result        return wrapper    else:        def decorator(func):            functools.wraps(func)            def wrapper2(*args, **kw):                print("begin %s" % arg)                result = None                if arg:                    result = func(*args, **kw)                print("end %s" % arg)                return result            return wrapper2        return decorator# 测试无参数调用@logdef example_function1():    print("Executing function1")# 测试带参数调用@log('execute')def example_function2():    print("Executing function2")# 测试调用example_function1()example_function2()

  • 1

Reply