Discuss / Python / 带参数和不带参数的decorator

带参数和不带参数的decorator

Topic source

lldhsds

#1 Created at ... [Delete] [Delete and Lock User]
from functools import wrapsdef log(text):    def decorator(func):        @wraps(func)        def wrapper(*args, **kwargs):            if callable(text):                print("Calling function %s" % func.__name__)                return func()            else:                print("Calling function %s, print %s" % (func.__name__, text))                return func()        return wrapper    if callable(text):        return decorator(text)    else:        return decorator@log("Custom log message")def function1():    return "Result from function1!"@logdef function2():    return "Result from function2!"print(function1())print(function2())

  • 1

Reply