defforce_think_status_false(func, _dict): @wraps(func) defwrapper(*args, **kwargs): for key, value in _dict.items(): kwargs[key] = value return func(*args, **kwargs) return wrapper
deflog_decorator(func): @wraps(func) defwrapper(*args, **kwargs): logging.info(f"Calling function {func.__name__} with args: {args}, kwargs: {kwargs}") result = func(*args, **kwargs) logging.info(f"Function {func.__name__} returned {result}") return result return wrapper
defauth_decorator(func): @wraps(func) defwrapper(*args, **kwargs): user = get_current_user() # 假设有一个函数可以获取当前用户 ifnot user.is_authenticated: raise PermissionError("You do not have permission to access this function.") return func(*args, **kwargs) return wrapper
defcache_decorator(func): cache = {} @wraps(func) defwrapper(*args): if args in cache: return cache[args] result = func(*args) cache[args] = result return result return wrapper
@cache_decorator deffibonacci(n): if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2)
defmy_decorator(func): defwrapper(*args, **kwargs): print("Something is happening before the function is called.") result = func(*args, **kwargs) print("Something is happening after the function is called.") return result return wrapper
@my_decorator defsay_hello(name): """Print a greeting message.""" print(f"Hello, {name}!")
defmy_decorator(func): @wraps(func) # 使用 @wraps(func) 保留元信息 defwrapper(*args, **kwargs): print("Something is happening before the function is called.") result = func(*args, **kwargs) print("Something is happening after the function is called.") return result return wrapper
@my_decorator defsay_hello(name): """Print a greeting message.""" print(f"Hello, {name}!")
Something is happening before the function is called. Hello, Alice! Something is happening after the function is called. say_hello Print a greeting message.